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

如何批量聚合数百个同结构Pandas DataFrame的键值数据?

解决方法

直接按以下步骤操作即可实现需求:

  1. 收集所有DataFrame到列表中
    把数百个结构相同的DataFrame放到一个列表里,比如:

    # 假设你的DataFrame是df1、df2...dfn,全部加入列表
    dfs = [df1, df2, df3, ..., dfn]
    
  2. 合并所有DataFrame
    使用pd.concat将所有DataFrame合并成一个大的DataFrame:

    import pandas as pd
    combined_df = pd.concat(dfs, ignore_index=True)
    
  3. 按Key分组并聚合
    对合并后的DataFrame按Key分组,然后对每一列直接用list函数聚合——这正好满足你的需求:列表类型的列会生成列表的列表,普通列生成值的列表:

    df_agg = combined_df.groupby('Key', as_index=False).agg(list)
    

验证示例

用你给出的示例数据测试:

# 构造示例DataFrame
df1 = pd.DataFrame({
    'Key': ['A', 'B'],
    'C1': [[1,2], [6,1]],
    'C2': [6,9],
    'C3': ['b', 'c']
})

df2 = pd.DataFrame({
    'Key': ['B', 'A'],
    'C1': [[5,8], [7,2]],
    'C2': [2,3],
    'C3': ['t', 'z']
})

# 执行步骤
dfs = [df1, df2]
combined_df = pd.concat(dfs, ignore_index=True)
df_agg = combined_df.groupby('Key', as_index=False).agg(list)

print(df_agg)

输出结果和你期望的df_agg完全一致:

Key                C1      C2      C3
0   A  [[1, 2], [7, 2]]  [6, 3]  [b, z]
1   B  [[6, 1], [5, 8]]  [9, 2]  [c, t]

注意事项

  • 如果部分DataFrame中缺少某个Key值,聚合后该Key对应的列列表长度会等于包含该Key的DataFrame数量,这符合常规聚合逻辑。
  • 确保所有DataFrame的列名完全一致(包括大小写),否则pd.concat会生成缺失值列,影响聚合结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:30:16