我有三个数据框:
df1:
col1 col2 col3
name1 human experID1
name2 mouse experID2
name3 human experID3
name4 mouse experID4
name5 human experID5
df2:
col1 col2 col4 col6
name1 human experID1 output1
name2 human experID2 output2
name3 human experID3 output3
name10 human experID10 output4
df3:
col1 col3 col7 col8
name1 happy human ref1
name2 sad mouse ref2
name3 angry human ref3
我想将它们结合起来:
第 1 列中的行必须保持不变,即由于 name1 出现在 col1 中的每个数据框中,因此在最终数据帧中应该出现三次。
我只想合并列,以便:如果列已经存在,则将数据添加到该列;否则,添加一个新列。
用"-"填充缺失的单元格
所以输出将是:
col1 col2 col3 col4 col6 col7 col8
name1 human experID1 - - - -
name2 mouse experID2 - - - -
name3 human experID3 - - - -
name4 mouse experID4 - - - -
name5 human experID5 - - - -
name1 human - experID1 output1 - -
name2 human - experID2 output2 - -
name3 human - experID3 output3 - -
name10 human - experID10 output4 - -
name1 - happy - - human ref1
name2 - sad - - mouse ref2
name3 - angry - - human ref3
在显示我尝试的内容方面: 我有三个数据框,df1,df2,df3
试图通过说以下内容来合并、连接、追加
:final_df = pd.DataFrame()
list_of_df = [df1,df2,df3]
#method 1
result = pd.concat(list_of_df)
#method 2
for each_df in list_of_dfs:
#this is where it started to go wrong
我尝试了此页面上的所有方法,但我认为它们没有做我想要它们做的事情(如果您希望我在此处添加此页面的代码,请告诉我,我只是认为既然它是错误的,指向链接更整洁(。
我认为从逻辑上讲,我想我想将每个数据框一个接一个地"追加"到主数据框中,以便行保持不变。如果有人可以举例,这只是在不合并我不明白的行的情况下合并列。
似乎,你只想附加
df1.append(df2, sort=False).append(df3, sort=False).fillna('-')
使用pd.concat
:
pd.concat([df1,df2,df3],sort=False).fillna('-')
col1 col2 col3 col4 col6 col7 col8
0 name1 human experID1 - - - -
1 name2 mouse experID2 - - - -
2 name3 human experID3 - - - -
3 name4 mouse experID4 - - - -
4 name5 human experID5 - - - -
0 name1 human - experID1 output1 - -
1 name2 human - experID2 output2 - -
2 name3 human - experID3 output3 - -
3 name10 human - experID10 output4 - -
0 name1 - happy - - human ref1
1 name2 - sad - - mouse ref2
2 name3 - angry - - human ref3