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

将包含多个DataFrame的大字典合并为单个DataFrame

将字典中的多个DataFrame合并为单个带分组标识的DataFrame

原数据定义

import pandas as pd
d = {
    'A':pd.DataFrame(
        {'Age' : [5,5,5],
         'Weight' : [5,5,5]}),
     'B':pd.DataFrame(
         {'Age' : [10,10,10],
        'Weight' : [10,10,10]}),
     'C':pd.DataFrame(
         {'Age' : [7,7,7],
        'Weight' : [10,10,100]}),
     }

目标格式

需要将上述字典转换为包含Team列的统一DataFrame,示例如下:

data = [
        ['A',5,5],
        ['A',5,5], 
        ['A',5,5],
        ['B',10,10],
        ['B',10,10], 
        ['B',10,10],
        ['C',7,10],
        ['C',7,10], 
        ['C',7,100],
        ]
df = pd.DataFrame(data, columns=['Team', 'Age', 'Weight'])

解决方案

方法一:使用pd.concat快速实现(推荐)

利用pandas内置的pd.concat方法,通过keys参数直接添加分组标识,再整理索引即可:

# 合并所有DataFrame,用字典的键作为分组层级
combined_df = pd.concat(d.values(), keys=d.keys(), names=['Team', '_'])
# 重置索引,将Team转为普通列并丢弃临时索引
combined_df = combined_df.reset_index(level='_', drop=True).reset_index()
# 调整列顺序与目标格式匹配
combined_df = combined_df[['Team', 'Age', 'Weight']]

运行后输出结果:

Team  Age  Weight
0    A    5       5
1    A    5       5
2    A    5       5
3    B   10      10
4    B   10      10
5    B   10      10
6    C    7      10
7    C    7      10
8    C    7     100

方法二:循环拼接(适合理解逻辑)

手动遍历字典的键值对,为每个DataFrame添加Team列后拼接:

df_list = []
for team, sub_df in d.items():
    # 为当前子DataFrame添加Team列
    sub_df['Team'] = team
    # 调整列顺序,将Team列放在首位
    sub_df = sub_df[['Team', 'Age', 'Weight']]
    df_list.append(sub_df)

# 拼接所有处理后的子DataFrame
final_df = pd.concat(df_list, ignore_index=True)

此方法逻辑直观,适合新手理解合并过程,最终结果与方法一完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:25:20