我正在尝试将 xlsx 文件从 Azure blob 存储读取到 pandas 数据帧,而不创建临时本地文件。看到很多类似的问题 例如Issues Reading Azure Blob CSV Into Python Pandas DF ,但尚未设法使建议的解决方案发挥作用。
下面的代码片段会导致 UnicodeDecodeError: 'utf-8' codec can't解码位置 14 中的字节 0x87: invalid start byte
异常。
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
对象存入内存,然后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.read_excel()
转换为 pandas 数据帧:
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)
关于python - 将 xlsx 从 azure blob 存储读取到 pandas dataframe,而不创建临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62370427/