将Python DataFrame作为CSV写入Azure Blob

我有两个关于从/向Azure blob读取和编写
Python对象的问题.

1)有人能告诉我如何将Python数据帧作为csv文件直接写入Azure Blob而不在本地存储吗?

我尝试使用函数create_blob_from_text& create_blob_from_stream
 但它们都不起作用.

将数据帧转换为字符串并使用create_blob_from_text函数
 将文件写入blob但是作为普通字符串而不是csv.

    df_b = df.to_string()
    block_blob_service.create_blob_from_text('test', 'OutFilePy.csv', df_b)  

2)如何直接将Azure blob存储中的json文件直接读入Python?

最佳答案

1) Can someone tell me how to write Python dataframe as csv file
directly into Azure Blob without storing it locally?

你可以使用pandas.DataFrame.to_csv方法.

示例代码:

from azure.storage.blob import (
    BlockBlobService
)
import pandas as pd
import io

output = io.StringIO()
head = ["col1" , "col2" , "col3"]
l = [[1 , 2 , 3],[4,5,6] , [8 , 7 , 9]]
df = pd.DataFrame (l , columns = head)
print df
output = df.to_csv (index_label="idx", encoding = "utf-8")
print(output)

accountName = "***"
accountKey = "***"
containerName = "test1"
blobName = "test3.json"

blobService = BlockBlobService(account_name=accountName, account_key=accountKey)

blobService.create_blob_from_text('test1', 'OutFilePy.csv', output)

输出结果:

《将Python DataFrame作为CSV写入Azure Blob》

2.How to directly read a json file in Azure blob storage directly into Python?

示例代码:

from azure.storage.blob import (
    BlockBlobService
)

accountName = "***"
accountKey = "***"
containerName = "test1"
blobName = "test3.json"

blobService = BlockBlobService(account_name=accountName, account_key=accountKey)

result = blobService.get_blob_to_text(containerName,blobName)

print(result.content)

输出结果:

《将Python DataFrame作为CSV写入Azure Blob》

希望它能帮到你.

    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞