如何在 python 中从 S3 中的 pandas 数据帧写入镶木地板文件

How to write parquet file from pandas dataframe in S3 in python

我有一个 pandas 数据框。我想将此数据框写入 S3 中的镶木地板文件。 我需要 same.I 尝试 google 的示例代码。但我无法获得有效的示例代码。

首先确保您安装了 pyarrow 或 fastparquet pandas。

然后安装boto3和aws cli。使用 aws cli 设置位于 .aws 文件夹的配置和凭证文件。

这是一个使用 pyarrow, and boto3 创建临时镶木地板文件然后发送到 AWS S3 的简单脚本。

不包括导入的示例代码:

def main():
    data = {0: {"data1": "value1"}}
    df = pd.DataFrame.from_dict(data, orient='index')
    write_pandas_parquet_to_s3(
        df, "bucket", "folder/test/file.parquet", ".tmp/file.parquet")


def write_pandas_parquet_to_s3(df, bucketName, keyName, fileName):
    # dummy dataframe
    table = pa.Table.from_pandas(df)
    pq.write_table(table, fileName)

    # upload to s3
    s3 = boto3.client("s3")
    BucketName = bucketName
    with open(fileName) as f:
       object_data = f.read()
       s3.put_object(Body=object_data, Bucket=BucketName, Key=keyName)

为了您的参考,我有以下代码工作。

s3_url = 's3://bucket/folder/bucket.parquet.gzip'
df.to_parquet(s3_url, compression='gzip')

要使用 to_parquet,您需要安装 pyarrowfastparquet。此外,请确保您的 configcredentials 文件中的信息正确,这些文件位于 .aws 文件夹。

编辑:此外,s3fs 是必需的。见

下面的函数在缓冲区中获取 parquet 输出,然后将 buffer.values() 写入 S3 而无需在本地保存 parquet

此外,由于您正在创建 s3 客户端,因此您可以使用 aws s3 密钥创建凭据,这些密钥可以存储在本地、气流连接或 aws secrets manager 中

def dataframe_to_s3(s3_client, input_datafame, bucket_name, filepath, format):

        if format == 'parquet':
            out_buffer = BytesIO()
            input_datafame.to_parquet(out_buffer, index=False)

        elif format == 'csv':
            out_buffer = StringIO()
            input_datafame.to_parquet(out_buffer, index=False)

        s3_client.put_object(Bucket=bucket_name, Key=filepath, Body=out_buffer.getvalue())

S3_client 只不过是一个 boto3 客户端 object.Hope 这有帮助!

礼貌-

对于 python 3.6+,AWS 有一个名为 aws-data-wrangler 的库,可帮助 Pandas/S3/Parquet

之间的集成

安装做;

pip install awswrangler

如果您想将 pandas 数据帧作为镶木地板文件写入 S3,请这样做;

import awswrangler as wr
wr.s3.to_parquet(
    dataframe=df,
    path="s3://my-bucket/key/my-file.parquet"
)