You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Dataframe存入S3后,能否通过索引查询指定Bucket的相关数据?

问题与解决方案

问题描述

本人习惯使用关系型数据库,但公司当前使用S3。了解到可以将Dataframe存入S3,但因习惯以列和字段视角看待数据,对Dataframe中的索引(Medical、Arrest、Offender、Jail)存在疑问:能否利用该索引实现精准查询,例如获取仅来自bucket2的Medical、Arrest、Offender、Jail相关数据?

当前Dataframe结构:

bucket1     bucket2      bucket3
Medical        1          3              5
Arrest         2          6              14
Offender       9          11             11
Jail           14         22             1

本人计划读取Excel文件转换为Dataframe后存入S3,尝试的代码如下:

import pandas as pd
import os  
import openpyxl

path = r'C:/Reports'
filename = 'scraper_report.xlsx'

wb = openpyxl.load_workbook(os.path.join(path, filename))
ws = wb['Totals_Summary']

data_rows = []
for row in ws['A2':'E15']:
    data_cols = []
    for cell in row:
        data_cols.append(cell.value)
    data_rows.append(data_cols)
print(data_rows)

from io import StringIO # python3; python2: BytesIO 
import boto3

bucket = 'my_bucket_name' # already created on S3
csv_buffer = StringIO()
df.to_csv(csv_buffer)
s3_resource = boto3.resource('s3')
s3_resource.Object(bucket, 'df.csv').put(Body=csv_buffer.getvalue())

解决方案

1. 利用索引实现精准查询

完全可以通过索引实现你要的精准查询,关键是在存储和读取Dataframe时处理好索引:

  • 存入S3时,pandas的to_csv默认会保留索引(将索引作为第一列存储),无需额外配置;
  • 从S3读取CSV时,指定index_col=0,让pandas把第一列识别为Dataframe的索引。

示例查询代码(读取S3上的文件后执行):

# 从S3读取CSV并恢复索引
s3_client = boto3.client('s3')
response = s3_client.get_object(Bucket='my_bucket_name', Key='df.csv')
df = pd.read_csv(response['Body'], index_col=0)

# 获取bucket2下的指定索引数据
target_data = df.loc[['Medical', 'Arrest', 'Offender', 'Jail'], 'bucket2']
print(target_data)

2. 优化Excel读取代码

你当前用openpyxl手动读取单元格的方式过于繁琐,直接用pandas读取Excel更高效,还能自动处理索引:

import pandas as pd
from io import StringIO
import boto3

path = r'C:/Reports'
filename = 'scraper_report.xlsx'

# 直接用pandas读取Excel指定工作表,自动识别索引和列
df = pd.read_excel(os.path.join(path, filename), sheet_name='Totals_Summary', index_col=0)

# 存入S3
bucket = 'my_bucket_name'
csv_buffer = StringIO()
# 保留索引存入CSV
df.to_csv(csv_buffer, index=True)
s3_resource = boto3.resource('s3')
s3_resource.Object(bucket, 'df.csv').put(Body=csv_buffer.getvalue())

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:10:38