You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将Azure文件共享中的CSV文件导入Pandas DataFrame

将Azure文件共享中的CSV文件导入Pandas DataFrame

实现步骤

  1. 筛选目标CSV文件:遍历文件共享内容时,仅保留后缀为.csv的文件(排除文件夹)
  2. 读取文件到内存:通过Azure存储SDK获取文件内容,直接存入内存流,无需写入本地磁盘
  3. 加载为DataFrame:将内存中的CSV数据导入Pandas DataFrame,多文件可合并为统一数据集

完整代码示例

from azure.storage.file import FileService
import pandas as pd
from io import StringIO

# 初始化Azure文件服务
file_service = FileService(account_name='your_storage_account', account_key='your_account_key')
share_name = 'your_file_share_name'
directory_path = 'target_directory_path'  # 替换为你的目标文件夹路径,比如'path/../..'

# 存储单个CSV的DataFrame列表
df_collection = []

# 遍历并处理CSV文件
generator = file_service.list_directories_and_files(share_name, directory_path)
for item in generator:
    # 仅处理后缀为.csv的文件
    if not item.is_directory and item.name.endswith('.csv'):
        # 获取文件内容为字符串
        csv_content = file_service.get_file_to_text(share_name, directory_path, item.name).content
        # 将字符串转为内存流,加载为DataFrame
        single_df = pd.read_csv(StringIO(csv_content))
        df_collection.append(single_df)
        print(f"已加载文件: {item.name}")

# 合并所有CSV为一个DataFrame(按需选择,适用于结构一致的CSV)
merged_df = pd.concat(df_collection, ignore_index=True)

# 验证结果
print(merged_df.head())

关键细节

  • 文件筛选:通过item.is_directory排除文件夹,endswith('.csv')锁定目标文件类型
  • 内存读取:使用StringIO将文本内容转为可读取流,避免本地磁盘IO开销
  • 数据集合并:若多个CSV结构匹配,pd.concat可快速合并为统一数据集,便于后续分析

内容的提问来源于stack exchange,提问作者Akansha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 16:20:28