【问题标题】:Convert CSV to Parquet in S3 with Python使用 Python 在 S3 中将 CSV 转换为 Parquet
【发布时间】:2021-10-22 20:16:58
【问题描述】:

我需要将 CSV 文件转换为 S3 路径中的 Parquet 文件。我正在尝试使用下面的代码,但没有发生错误,代码执行成功并且不转换 CSV 文件

import pandas as pd
import boto3
import pyarrow as pa
import pyarrow.parquet as pq

s3 = boto3.client("s3", region_name='us-east-2', aws_access_key_id='my key id',
                  aws_secret_access_key='my secret key')

obj = s3.get_object(Bucket='my bucket', Key='test.csv')
df = pd.read_csv(obj['Body'])
table = pa.Table.from_pandas(df)
pq.write_to_dataset(table=table, root_path="test.parquet")

【问题讨论】:

  • 您会考虑使用 Amazon Athena 来转换文件格式,而不是自己做吗?见:Converting to Columnar Formats - Amazon Athena
  • 只有这个脚本不起作用:pq.write_to_dataset(table=table, root_path="test.parquet") 不在 s3 上创建 parquet 文件
  • 您的程序中没有将数据写入 S3 的代码。我可以看到它正在将 CSV 文件读入 Pandas 数据帧,但没有任何东西可以写入到 S3。
  • 它正在本地写入一个名为 test.parquet 的文件。然后,您必须将该文件上传到镶木地板。

标签: python amazon-web-services csv amazon-s3 parquet


【解决方案1】:

Python 中的 AWS CSV 到 Parquet 转换器

此脚本从 Amazon S3 获取文件并将其转换为 Parquet 版本以供以后的查询作业使用,然后将其上传回 Amazon S3。

import numpy 
import pandas 
import fastparquet

def lambda_handler(event,context):

    #identifying resource
    s3_object = boto3.client('s3', region_name='us-east-2')

    #access file

    get_file = s3_object.get_object(Bucket='ENTER_BUCKET_NAME_HERE', Key='CSV_FILE_NAME.csv')
    
    get = get_file['Body']

    df = pandas.DataFrame(get)

    #convert csv to parquet function
    def conv_csv_parquet_file(df):
    
        converted_data_parquet = df.to_parquet('converted_data_parquet_version.parquet')
    
    conv_csv_parquet_file(df)

    print("File converted from CSV to parquet completed")

    #uploading the parquet version file

    s3_path = "/converted_to_parquet/" + converted_data_parquet

    put_response = s3_resource.Object('ENTER_BUCKET_NAME_HERE',converted_data_parquet).put(Body=converted_data_parquet)

Python Library Boto3 允许 lambda 从 S3 获取 CSV 文件,然后 Fast-Parquet(或 Pyarrow)将 CSV 文件转换为 Parquet。

来自-https://github.com/ayshaysha/aws-csv-to-parquet-converter.py

【讨论】:

    猜你喜欢
    • 2019-07-05
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-25
    相关资源
    最近更新 更多