我有以下内容。 2 个 pandas 数据框:
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]})
如果 df1 和 df2 中的 col1
和 col2
具有相同的值,如何将 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 在这些列中具有相同值的行。然而, Pandas loses the index合并时。您可以在合并之前使用 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
关于python - 更改 pandas 数据框中的值与另一个数据框中存在同一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38863830/