python - 如何像数据框中的 vlookup 一样替换行值
问题描述
我必须df
df1 with almost 100k rows
Name1 Amount1 Type1 Balance1
A 10 R 2
B 10 D 0
B 5 R 10
C 5 R 0
当 df2 与这两个匹配时,我需要替换该行Name and Type
是 df2 - 通常只有 6 行
Name2 Amount2 Type2 Balance2
B 5000 D 200
C 5 R 100
D 10 Q 0
当 [Name1, Type1] == [Name2, Type2] 时,我想将 Amount2 复制到 Amount1 并将 Balance2 复制到 Balance1,这是更好的方法吗?
期望的输出:df1 的所有 100k 行都应保留在 df1 本身中。不应将 df2 中不匹配的行添加为 df1 中的行(将被忽略)。Amount2 和 Balance2 的新值应替换 Amount1 和 Balance2。
Name1 Amount1 Type1 Balance1
A 10 R 2
B 5000 D 100 <---Both Amount and balance changed
B 5 R 10 <---Type1 != Type2 in this case
C 5 R 100 <---Balance changed
解决方案
您可以将相应的列设置为索引并使用update
:
# make sure df1 and df2 has the same column names
df2.columns=df1.columns
# set index
df1 = df1.set_index(['Name1','Type1'])
df1.update(df2.set_index(['Name1','Type1']))
# reset index
df1 = df1.reset_index()
输出:
Name1 Type1 Amount1 Balance1
0 A R 10.0 2.0
1 B D 5000.0 200.0
2 B R 5.0 10.0
3 C R 5.0 100.0