我有两个不同长度的 pandas 数据帧,当两列匹配时,我需要有条件地将值从一个数据帧覆盖到另一个数据帧。
df1.val = df2.val where df1.val == null and df1.key1 == df2.key1 and df1.key2 == df2.key2
df1
和df2
具有非常不同的列和行长度集,除了 key1
, key2
,和val
。唯一可以保证的是对于每个 (key1, key2)
在df1
,正好有一个(key1, key2)
在df2
.
到目前为止,我一直在走这条路
df1.loc[df1.val.isnull(), "val"] = df2.val
尝试设置索引以匹配,但我没有任何进展。
我知道有一些加入,但我在这方面也没有取得任何进展。一些语法帮助将不胜感激。
编辑数据:
DF1:
First Last Val Random1 ...
John Smith 4 x
Todd Smith 5 Nan
John Todd Nan z
DF2:
First Last Val Random2 ...
John Smith 7 4
Todd Smith 6 9
John Todd 3 3
Eric Smith 5 2
结果:
First Last Val Random1 ...OtherDF1Cols...
John Smith 4 x
Todd Smith 5 Nan
John Todd 3 z
最佳答案
首先设置索引,然后填充
DF1.set_index(['First', 'Last']).fillna(DF2.set_index(['First', 'Last']))
Val
First Last
John Smith 4.0
Todd Smith 5.0
John Todd 3.0
使用combine_first
包含两个数据帧中的所有内容
DF1.set_index(['First', 'Last']).combine_first(DF2.set_index(['First', 'Last']))
Val
First Last
Eric Smith 5.0
John Smith 4.0
Todd 3.0
Todd Smith 5.0
<小时/>
或者,仅更新 Val
列,并限制为仅从第一行开始
d1 = DF1.set_index(['First', 'Last'])
d2 = DF2.set_index(['First', 'Last'])
print(d1.combine_first(d2[['Val']]).loc[d1.index].reset_index())
First Last Val
0 John Smith 4.0
1 Todd Smith 5.0
2 John Todd 3.0
<小时/>
使用更新
的选项
d1 = DF1.set_index(['First', 'Last'])
d2 = DF2.set_index(['First', 'Last'])
d1.update(d2.Val, overwrite=False)
d1.reset_index()
First Last Val
0 John Smith 4.0
1 Todd Smith 5.0
2 John Todd 3.0
关于python - 有条件地在多个索引上加入 pandas DF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43286144/