【问题标题】:concat two dataframes and exclude overlapping rows连接两个数据帧并排除重叠行
【发布时间】:2023-04-06 23:59:01
【问题描述】:

我正在尝试连接两个数据帧 df1df2

输入

        name   age   hobby   married
index
0       jack   20    hockey  yes
1       ben    19    chess   no
2       lisa   30    golf    no
        name   age    hobby      job
index
0       jack   20     hockey     student
1       anna   34     football   finance
2       dan    26     golf       retail

我想在多个列上匹配,所以假设['name', 'age'],得到df

输出

        name   age   hobby     married   job
index
0       jack   20    hockey    yes       student
1       ben    19    chess     no        /
2       lisa   30    golf      no        /
3       anna   34    football  /         finance
4       dan    26    golf      /         retail

是否可以通过使用 concat 来做到这一点?因为我不知道如何匹配键列表以避免重叠行...

【问题讨论】:

    标签: python pandas dataframe merge concat


    【解决方案1】:

    你可以这样做:

    In [1077]: res = df1.merge(df2, on=['name', 'age'], how='outer')
    In [1079]: res['hobby'] = res.hobby_x.combine_first(res.hobby_y)
    
    In [1081]: res.drop(['hobby_x', 'hobby_y'], axis=1, inplace=True)
    
    In [1082]: res
    Out[1082]: 
       name  age married      job     hobby
    0  jack   20     yes  student    hockey
    1   ben   19      no      NaN     chess
    2  lisa   30      no      NaN      golf
    3  anna   34     NaN  finance  football
    4   dan   26     NaN   retail      golf
    

    【讨论】:

      【解决方案2】:

      这是另一种方式:

      df1.set_index(['name', 'age'])\
         .combine_first(df2.set_index(['name', 'age']))\
         .reset_index()\
         .fillna('/')
      

      输出:

         name  age     hobby      job married
      0  anna   34  football  finance       /
      1   ben   19     chess        /      no
      2   dan   26      golf   retail       /
      3  jack   20    hockey  student     yes
      4  lisa   30      golf        /      no
      

      让我们在 pandas 中使用内在数据对齐,方法是将索引设置为要“加入”的列,然后使用 combine_first 数据帧。

      【讨论】:

      • @gardangerous 快乐编码。保持安全并保持健康。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      相关资源
      最近更新 更多