![](/img/trans.png)
[英]How to remove rows in a Pandas dataframe if the same row exists in another dataframe?
[英]Changing value in pandas dataframe is same row is present in another dataframe
我有傻瓜。 2个熊猫数据框:
df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14], 'col3' : [0,2,0,-1,0]})
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12], 'col6' : [20, 31, 12]})
如果col1
和col2
在df1和df2中具有相同的值,如何将df1中的col3
中的值更改为0。 df1的结果应如下所示:
col1 col2 col3
0 1 10 0
1 2 11 0
2 3 12 0
3 4 13 -1
4 5 14 0
如果在col1
和col2
上合并两个DataFrame,则结果DataFrame将具有行,其中两个DataFrame在这些列中具有相同的值。 但是,大熊猫在合并时会失去索引 。 您可以在合并之前使用reset_index
来保留索引并在.loc
使用该索引:
df1.loc[df1.reset_index().merge(df2, on=['col1', 'col2'])['index'], 'col3'] = 0
df1
Out:
col1 col2 col3
0 1 10 0
1 2 11 0
2 3 12 0
3 4 13 -1
4 5 14 0
快速的numpy解决方案。 i
从df1
获得每一行的索引,而从df2
另一行的索引。 我使用==
来确定哪些单元格相等。 all(2)
确定一行中的所有单元格是否等于另一行中的所有单元格。 如果为true,则对应的一组索引表示一个匹配项。 因此, i[0][matches]
告诉我df1
中与i[1][matches]
表示的df2
中的行匹配的所有行。 但是我只需要更改df1
值,所以我只使用i[0][matches]
在第3列上切片df1
,然后分配0
。
def pir(df1, df2):
i = np.indices((len(df1), len(df2)))
matches = (df2.values[i[1], :2] == df1.values[i[0], :2]).all(2)
df = df1.copy()
df.iloc[i[0][matches], 2] = 0
return df
pir(df1, df2)
def ayhan(df1, df2):
df1 = df1.copy()
df1.loc[df1.reset_index().merge(df2, on=['col1', 'col2'])['index'], 'col3'] = 0
return df1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.