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

如何用Python Pandas提取Column A重复分组行并导出为CSV

按Column A分组并导出每个分组为CSV文件

原始数据

column Acolumn B
A2
A2
A3
B2
B3
B4
C2
C2
D2
D2
D3

实现步骤

1. 导入依赖并加载数据

先确保安装了pandas,然后加载目标DataFrame(以下示例直接构造你提供的样本数据,实际场景也可以从本地文件读取):

import pandas as pd

# 构造样本数据
data = {
    'column A': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'D', 'D', 'D'],
    'column B': [2, 2, 3, 2, 3, 4, 2, 2, 2, 2, 3]
}
df = pd.DataFrame(data)

2. 分组并导出CSV

用groupby按column A拆分数据,遍历每个分组后直接导出为独立CSV文件:

# 按column A分组
groups = df.groupby('column A')

# 遍历分组并导出
for group_name, group_df in groups:
    # 用分组名命名文件,避免重名
    file_path = f'group_{group_name}.csv'
    # 导出时不保留索引列
    group_df.to_csv(file_path, index=False)

3. 导出结果说明

执行代码后,当前目录会生成4个CSV文件:group_A.csv、group_B.csv、group_C.csv、group_D.csv,每个文件对应你期望的独立分组数据。比如group_A.csv内容如下:

column Acolumn B
A2
A2
A3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:31:03