比较两个数据帧并根据匹配的列值从df中删除行

问题描述 投票:1回答:1

我有两只pandas 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个回答
1
投票

使用列mergepidscore,但首先通过reset_index创建索引列,最后再次创建pid索引,并为DataFrame添加reindex的新df2.columns的相同列:

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
© www.soinside.com 2019 - 2024. All rights reserved.