Skip to main content
 首页 » 编程设计

python之合并 pandas 数据帧 : keep row redundancy while removing column redundancy

2025年05月04日21lonelyxmas

我有三个数据框:

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. 第 1 列中的行必须保持不变,即由于 name1 出现在 col1 的每个数据帧中,它应该在最终数据帧中出现三次。

  2. 我只想合并列以便:如果该列已存在,则将数据添加到该列;否则,添加一个新列。

  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('-')