【问题标题】:How to store pandas dataframe data to azure blobs using python?如何使用 python 将 pandas 数据帧数据存储到 azure blob?
【发布时间】:2019-07-06 23:07:19
【问题描述】:

我想以 parquet 文件格式将处理过的数据存储在 pandas 数据框中的 azure blob。但在上传到 blob 之前,我必须将其作为 parquet 文件存储在本地磁盘中,然后再上传。我想将 pyarrow.table 写入 pyarrow.parquet.NativeFile 并直接上传。谁能帮我这个。下面的代码工作正常:

import pyarrow as pa
import pyarrow.parquet as pq

battery_pq = pd.read_csv('test.csv')
########一些数据处理
battery_pq = pa.Table.from_pandas(battery_pq)
pq.write_table(battery_pq,'example.parquet')
block_blob_service.create_blob_from_path(container_name,'example.parquet','example.parquet')

需要在内存中创建文件(I/O文件类型对象),然后上传到blob。

【问题讨论】:

标签: python pandas azure blob parquet


【解决方案1】:

您可以为此使用io.BytesIO,或者Apache Arrow 也提供其本机实现BufferOutputStream。这样做的好处是,它写入流而无需通过 Python 的开销。因此制作的副本更少,GIL 也被释放。

import pyarrow as pa
import pyarrow.parquet as pq

df = some pandas.DataFrame
table = pa.Table.from_pandas(df)
buf = pa.BufferOutputStream()
pq.write_table(table, buf)
block_blob_service.create_blob_from_bytes(
    container,
    "example.parquet",
    buf.getvalue().to_pybytes()
)

【讨论】:

【解决方案2】:

有一个新的python SDK 版本。 create_blob_from_bytes 现在是旧版

import pandas as pd
from azure.storage.blob import BlobServiceClient
from io import BytesIO

blob_service_client = BlobServiceClient.from_connection_string(blob_store_conn_str)
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_path)

parquet_file = BytesIO()
df.to_parquet(parquet_file, engine='pyarrow')
parquet_file.seek(0)  # change the stream position back to the beginning after writing

blob_client.upload_blob(
    data=parquet_file
)

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2020-07-01
    • 2021-12-21
    • 2021-11-10
    相关资源
    最近更新 更多