【问题标题】:Find duplicate rows based on the first two columns from a data frame and add its third column根据数据框中的前两列查找重复行并添加其第三列
【发布时间】:2020-02-10 10:09:06
【问题描述】:

我有两个数据框 df1 和 df2,每个数据框有三列。我想根据前两列查找重复行,并将 df1 中重复条目的第三列替换为相应重复条目中第三列的总和

简单示例

df1
col1 col2 col3
80.3    30.3    15
80.3    30.2    15
80.3    30.4    15
80.3    30      15
80.3    29.9    15
80.4    29.9    10
df2
col1 col2 col3
80.3    30.3    5
80.3    30.2    5
80.3    30.4    5
80.3    30      5
80.3    29.9    5
expected result
80.3    30.3    20
80.3    30.2    20
80.3    30.4    20
80.3    30      20
80.3    29.9    20
80.4    29.9    10

我应该如何在 col1 和 col2 中引入 0.01 的容差级别来查找重复项?

【问题讨论】:

    标签: python pandas duplicates


    【解决方案1】:

    试试这个,不要容忍:

    pd.concat([df1, df2]).groupby(["col1", "col2"], as_index=False)["col3"].sum()
       col1  col2  col3
    0  80.3  29.9    20
    1  80.3  30.0    20
    2  80.3  30.2    20
    3  80.3  30.3    20
    4  80.3  30.4    20
    5  80.4  29.9    10
    

    关于容忍度,请参阅@jezrael 答案。

    【讨论】:

      【解决方案2】:

      没有容差的解决方案是concat 和聚合sum

      df = pd.concat([df1, df2]).groupby(['col1','col2'], as_index=False, sort=False).sum()
      print (df)
         col1  col2  col3
      0  80.3  30.3    20
      1  80.3  30.2    20
      2  80.3  30.4    20
      3  80.3  30.0    20
      4  80.3  29.9    20
      5  80.4  29.9    10
      

      通过cut 进行bining,具有容差的解决方案更加复杂:

      df2 = (pd.concat([df1, df2])
               .assign(c1 = lambda x: pd.cut(x['col1'], 
                                             np.arange(x['col1'].min(), 
                                                       x['col1'].max()+0.01, 0.02), right = False),
                       c2 = lambda x: pd.cut(x['col2'], 
                                             np.arange(x['col2'].min(), 
                                                       x['col2'].max()+0.01, 0.02), right = False))
               .groupby(['c1','c2'], sort=False)
               .agg({'col1':'first', 'col2':'first', 'col3':'sum'})
               .dropna()
               .reset_index(drop=True))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        相关资源
        最近更新 更多