如何使用 python 将 Pandas 数据帧数据存储到 azure blob?

Bha*_*rla 3 python blob azure pandas parquet

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

import pyarrow as pa
import pyarrow.parquet as pq

battery_pq = pd.read_csv('test.csv')
Run Code Online (Sandbox Code Playgroud) ######## 一些数据处理
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')
Run Code Online (Sandbox Code Playgroud)

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

Uwe*_*orn 5

您可以为此使用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()
)
Run Code Online (Sandbox Code Playgroud)


Rom*_*man 5

有一个新的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
)
Run Code Online (Sandbox Code Playgroud)