【发布时间】:2019-05-22 20:11:47
【问题描述】:
我在 pandas(python) 中有两个 DataFrame
df1
UniqueKey ValueFix ValueChange
A 10 100
B 15 0
C 20 150
D 15 0
E 10 100
df2
UniqueKey ValueFix ValueChange
B 15 300
D 15 400
我想根据 df2 中的值更新 df1,但 只更新“值更改”列中的值。因为实际上我不应该更新不在 df2 中的行。我怎样才能做到这一点?我迷路了。 所以我想要的结果是:
UniqueKey ValueFix ValueChange
A 10 100
B 15 300
C 20 150
D 15 400
E 10 100
在我看来,唯一的解决方案是使用 UniqueKey-ValuChange 以某种方式将 df2 转换为字典 并且 with 循环通过 df1 中的 ValueChange 条件,例如 'If row[Value_change] in dictionary then replace with value from dictionary.
但我不知道如何使用 pandas 来做到这一点
【问题讨论】:
-
使用
df1=df1.set_index('UniqueKey')设置索引并对df2做同样的事情,然后df1.update(df2) -
df2.set_index('UniqueKey').combine_first(df1.set_index('UniqueKey')).reset_index() -
但是如果我只想更新“值更改”列中的值该怎么办?
-
@Artem 我仍然认为我的方式可行。你试过了吗?
-
@anky_91 我指定了我的问题以避免混淆。我猜您的解决方案将更新 df1 中的所有行和列。我只需要更新特定值(在这种情况下 - df1 中的“值更改”列中的零)