从dict合并多个数据框

时间:2020-05-22 14:09:09

标签: python pandas

给出DataFrames的以下命令:

{

"01_2012": 
"Acc"  "B"   "F"
"011"   23   43
"012" 4324  432

"01_2013": 
"Acc" "B" "  F"
"011"   23   224
"012" 4324  453,

"01_2014": 
"Acc"  "B" "  F"
"011"   23    312
"012" 4324   500
"013: 4322   2120
}

是否可以合并“ Acc”键上的所有数据框,并将dict键名称添加到其他cols?

因此最终结果将是:

"Acc"  "B_01_2012"  "F_01_2012" "B_01_2013" "F_01_2013" "B_01_2014" "F_01_2014" 
"011"   23               43            ...
"012"   4324            432
"013" Nan                Nan           Nan         Nan      4322        2120

1 个答案:

答案 0 :(得分:1)

看起来你可以做一个连环画:

pd.concat([d.set_index('Acc') for d in df_dicts.values()],
          keys=df_dicts.keys, axis=1)

pd.concat([d.set_index('Acc').add_suffix(f'_{k}')
            for k,d in df_dicts.items()],
          axis=1)