我想在索引和的“类型”列上连接3个数据框,其中缺少一些索引值(dfb和dfc的索引不完整,而dfa的索引完整)。当我进行合并时,某些列会消失,如下所示。 (我希望最终的数据帧具有MultiIndex,以便我可以按类型提取串联数据帧的部分,并且df ['type2']应该具有排序的索引)。
我尝试了使用各种参数的concat,但是没有用。
dfa=pd.DataFrame({'type':['type1','type1','type2'],'a':[10,20,30]},index=[1,2,3])
dfb=pd.DataFrame({'type':['type1','type2'],'b':[11,21]},index=[2,3])
dfc=pd.DataFrame({'type':['type3'],'c':[33]},index=[3])
dfa
dfb
dfc
pd.concat([dfa,dfb,dfc],axis=0,keys=['type']) #wrong. columns b and c disappear!
我想要一个有效的解决方案,因为我有5个数据框,其中有2000个“类型”,每个索引的大小都在10K左右
所需数据框的示例:
pd.DataFrame({'a':[10,20,30,np.nan],'b':[np.nan,11,21,np.nan],'c':
[np.nan,np.nan,np.nan,33],'type':['type1','type1','type2','type3']},index=
[1,2,3,3])
答案 0 :(得分:1)
您没有定义足够的键来匹配串联的数据帧数量的问题。
尝试一下:
pd.concat([dfa, dfb, dfc], axis=0, keys=['type_a', 'type_b', 'type_c'])
输出:
a b c type
type_a 1 10.0 NaN NaN type1
2 20.0 NaN NaN type1
3 30.0 NaN NaN type2
type_b 2 NaN 11.0 NaN type1
3 NaN 21.0 NaN type2
type_c 3 NaN NaN 33.0 type3
或将keys
参数全部排除:
pd.concat([dfa, dfb, dfc], axis=0)
输出:
a b c type
1 10.0 NaN NaN type1
2 20.0 NaN NaN type1
3 30.0 NaN NaN type2
2 NaN 11.0 NaN type1
3 NaN 21.0 NaN type2
3 NaN NaN 33.0 type3
答案 1 :(得分:1)
创建df后:
dfa=pd.DataFrame({'type':['type1','type1','type2'],'a':[10,20,30]},index=[1,2,3])
dfb=pd.DataFrame({'type':['type1','type2'],'b':[11,21]},index=[2,3])
dfc=pd.DataFrame({'type':['type3'],'c':[33]},index=[3])
您可以像这样使用merge
和reset_index
:
dfs = [dfa, dfb, dfc] # ... add as many df as you wish
res = dfs[0].reset_index()
for i in range(1,len(dfs)):
res = res.merge(dfs[i].reset_index(), how='outer', left_on=['index','type'], right_on=['index','type'])
res = res.set_index('index')
print(res)
结果将是:
type a b c
index
1 type1 10.0 NaN NaN
2 type1 20.0 11.0 NaN
3 type2 30.0 21.0 NaN
3 type3 NaN NaN 33.0