繁体   English   中英

从 azure blob 存储读取 xlsx 到 pandas dataframe 而不创建临时文件

[英]Read xlsx from azure blob storage to pandas dataframe without creating temporary file

我正在尝试从 Azure blob 存储读取 xlsx 文件到 pandas dataframe 而不创建临时本地文件。 I have seen many similar questions, eg Issues Reading Azure Blob CSV Into Python Pandas DF , but haven't managed to get the proposed solutions to work.

下面的代码片段导致UnicodeDecodeError: 'utf-8' codec can't decode byte 0x87 in position 14: invalid start byte exception。

from io import StringIO
import pandas as pd
from azure.storage.blob import BlobClient, BlobServiceClient

blob_client = BlobClient.from_blob_url(blob_url = url + container + "/" + blobname, credential = token)   
blob = blob_client.download_blob().content_as_text()   
df = pd.read_excel(StringIO(blob))

使用临时文件,我确实设法使其与以下代码片段一起工作:

blob_service_client = BlobServiceClient(account_url = url, credential = token)
blob_client = blob_service_client.get_blob_client(container=container, blob=blobname)

with open(tmpfile, "wb") as my_blob:
    download_stream = blob_client.download_blob()
    my_blob.write(download_stream.readall())

data = pd.read_excel(tmpfile)

与您已经完成的类似,我们可以使用download_blob()StorageStreamDownloader object 放入 memory,然后context_as_text()将内容解码为字符串。

然后我们可以从 CSV StringIO缓冲区读取内容到 pandas Dataframe 与pandas.read_csv()

from io import StringIO
import pandas as pd
from azure.storage.blob import BlobClient, BlobServiceClient
import os

connection_string = os.getenv('AZURE_STORAGE_CONNECTION_STRING')

blob_service_client = BlobServiceClient.from_connection_string(connection_string)

blob_client = blob_service_client.get_blob_client(container="blobs", blob="test.csv")

blob = blob_client.download_blob().content_as_text()

df = pd.read_csv(StringIO(blob))

更新

如果我们正在使用 XLSX 文件,请使用content_as_bytes()返回字节而不是字符串,并转换为 pandas dataframe 和pandas.read_excel()

from io import StringIO
import pandas as pd
from azure.storage.blob import BlobClient, BlobServiceClient
import os

connection_string = os.getenv('AZURE_STORAGE_CONNECTION_STRING')

blob_service_client = BlobServiceClient.from_connection_string(connection_string)

blob_client = blob_service_client.get_blob_client(container="blobs", blob="test.xlsx")

blob = blob_client.download_blob().content_as_bytes()

df = pd.read_excel(blob)

由于content_as_text()默认使用 UTF-8 编码,这可能是解码字节时导致UnicodeDecodeError的原因。

如果我们将编码设置为None ,我们仍然可以将它与pandas.read_excel()一起使用:

blob = blob_client.download_blob().content_as_text(encoding=None)

df = pd.read_excel(blob)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM