【问题标题】:Compare two dataframes and remove rows from a df based on a matching column value比较两个数据帧并根据匹配的列值从 df 中删除行
【发布时间】:2018-04-19 13:46:51
【问题描述】:

我有两只熊猫 df,看起来像这样:

df1:

pid Name score age
100  Ram     3  36
101 Tony     2  40
101 Jack     4  56
200 Jill     6  30

df2
pid Name score age
100  Ram     3  36
101 Tony     2  40
101 John     4  51
101 Jack     9  32
200 Jill     6  30

两个 df 都使用 'pid' 进行索引。我想根据“分数”列比较 df1 和 df2。即,我只需要保留 df2 中与 df1 在索引和分数值上匹配的那些行。

我的预期结果应该是

new df2:
pid Name index age
100  Ram     3  36
101 Tony     2  40
101 John     4  51
200 Jill     6  30 

非常感谢您在这方面的任何帮助。

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    通过列pidscore 使用merge,但首先通过reset_index 从索引创建列,最后再次创建pid 索引,对于新DataFrame 的相同列,通过@ 添加reindex 987654331@:

    df = (pd.merge(df1.reset_index(), 
                   df2.reset_index(), on=['score', 'pid'], how='left', suffixes=['_',''])
            .set_index('pid')
            .reindex(columns=df2.columns))
    
    print (df)
         Name  score  age
    pid                  
    100   Ram      3   36
    101  Tony      2   40
    101  John      4   51
    200  Jill      6   30
    

    输入:

    print (df1)
         Name  score  age
    pid                  
    100   Ram      3   36
    101  Tony      2   40
    101  Jack      4   56
    200  Jill      6   30
    
    print (df2)
         Name  score  age
    pid                  
    100   Ram      3   36
    101  Tony      2   40
    101  John      4   51
    101  Jack      9   32
    200  Jill      6   30
    

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 2021-11-02
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多