Python S3选择在CSV中检索标题
我正在尝试使用以下代码从存储在S bucket中的CSV中获取记录的子集:Python S3选择在CSV中检索标题,python,csv,amazon-s3,export-to-csv,boto3,Python,Csv,Amazon S3,Export To Csv,Boto3,我正在尝试使用以下代码从存储在S bucket中的CSV中获取记录的子集: s3 = boto3.client('s3') bucket = bucket file_name = file sql_stmt = """SELECT S.* FROM s3object S LIMIT 10""" req = s3.select_object_content( Bucket=bucket, Key=file, ExpressionType='SQL', Expr
s3 = boto3.client('s3')
bucket = bucket
file_name = file
sql_stmt = """SELECT S.* FROM s3object S LIMIT 10"""
req = s3.select_object_content(
Bucket=bucket,
Key=file,
ExpressionType='SQL',
Expression=sql_stmt,
InputSerialization = {'CSV': {'FileHeaderInfo': 'USE'}},
OutputSerialization = {'CSV': {}},
)
records = []
for event in req['Payload']:
if 'Records' in event:
records.append(event['Records']['Payload'])
elif 'Stats' in event:
stats = event['Stats']['Details']
file_str = ''.join(r.decode('utf-8') for r in records)
select_df = pd.read_csv(StringIO(file_str))
df = pd.DataFrame(select_df)
print(df)
这成功地生成了记录,但在标题上遗漏了
我在这里读到,s3select根本不产生头。那么,是否可以以任何其他方式在S3中检索CSV文件的头?Change InputSerialization={'CSV':{FileHeaderInfo:Use}
要输入序列化={'CSV':{FileHeaderInfo:NONE}
然后,它将打印全部内容,包括标题
说明:
FileHeaderInfo接受NONE或USE或IGNORE中的一个
使用“无”选项而不是“使用”,它将同时打印标题,因为“无”表示您也需要标题进行处理
这是参考资料
我希望这会有所帮助。Red Boy的解决方案不允许您在查询中使用列名,而是必须使用列索引。 这对我不好,所以我的解决方案是执行另一个查询,只获取标题并将其与实际查询结果连接起来。这适用于JavaScript,但同样适用于Python:
const params = {
Bucket: bucket,
Key: "file.csv",
ExpressionType: 'SQL',
Expression: `select * from s3object s where s."date" >= '${fromDate}'`,
InputSerialization: {'CSV': {"FileHeaderInfo": "USE"}},
OutputSerialization: {'CSV': {}},
};
//s3 select doesn't return the headers, so need to run another query to only get the headers (see '{"FileHeaderInfo": "NONE"}')
const headerParams = {
Bucket: bucket,
Key: "file.csv",
ExpressionType: 'SQL',
Expression: "select * from s3object s limit 1", //this will only get the first record of the csv, and since we are not parsing headers, they will be included
InputSerialization: {'CSV': {"FileHeaderInfo": "NONE"}},
OutputSerialization: {'CSV': {}},
};
//concatenate header + data -- getObject is a method that handles the request
return await this.getObject(s3, headerParams) + await this.getObject(s3, params);
简而言之
FileHeaderInfo字符串-描述输入的第一行
有效值为:
无:第一行不是标题
忽略:第一行是标题,
但不能使用标题值来指示表达式中的列。您可以使用列位置(如_1,_2,…)来指示从对象s中选择s._1的列
用法:第一行是
标题,您可以使用标题值标识表达式中的列“从对象选择名称”
如果我读取的是拼花文件而不是csv,那么有没有办法获得结果中的标题?我目前只得到拼花地板文件的行。当我在sql查询中添加where子句时,这个解决方案不适用于我