我有两个 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
非常感谢在这方面的任何帮助。
最佳答案
使用merge
按 pid
和 score
列,但首先根据 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
关于python-3.x - 比较两个数据帧并根据匹配的列值从 df 中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49913407/