我有三个数据框:
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的每个数据帧中,因此它应在最终数据帧中出现3次。
我只想合并这些列,以便:如果该列已经存在,则将数据添加到该列;否则,添加一个新列。
用“-”填充缺少的单元格
因此输出为:
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
我尝试了this页上的所有方法,但我不认为它们可以执行我想要的操作(请让我知道是否要在此处添加此页中的代码,我只是认为这是错误的,所以指向链接更整洁了)。
从逻辑上讲,我想我想将每个数据帧一个接一个地“追加”到主数据帧,因此行保持不变。如果有人可以显示一个示例,那只是合并列而不合并我不理解的行。
最佳答案
似乎您只想附加
df1.append(df2, sort=False).append(df3, sort=False).fillna('-')
关于python - 合并 Pandas 数据帧:保留行冗余,同时删除列冗余,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58410487/