Python 填充与另一数据帧的索引和列匹配的缺失值
我目前在使用不同的数据帧填充数据帧缺少的值时遇到问题 数据样本: df1 df2 我已经尝试过在这方面遵循解决方案,但似乎只有当您正在查找的值在您要加入的两个数据帧中都存在时才有可能 我的尝试Python 填充与另一数据帧的索引和列匹配的缺失值,python,pandas,Python,Pandas,我目前在使用不同的数据帧填充数据帧缺少的值时遇到问题 数据样本: df1 df2 我已经尝试过在这方面遵循解决方案,但似乎只有当您正在查找的值在您要加入的两个数据帧中都存在时才有可能 我的尝试 mask = df1["B"].isnull() df1.loc[mask, "B"] = df2[df1.loc[mask, "A"]].values 错误: "None of [Index(['d', 'a', 'f'], dtype='object')] are in the [columns]"
mask = df1["B"].isnull()
df1.loc[mask, "B"] = df2[df1.loc[mask, "A"]].values
错误:
"None of [Index(['d', 'a', 'f'], dtype='object')] are in the [columns]"
预期结果:
A B C
b 1.0 1.0
d 4.0 8.0
c 2.0 2.0
a 3.0 7.0
f NaN NaN
另外,它可以用来填充两列吗?您可以在这里使用,它的目的正是通过与另一个数据帧的列匹配来填充NaN
s:
df1.set_index('A').combine_first(df2.set_index('A')).reset_index()
A B C
0 a 3.0 7.0
1 b 1.0 1.0
2 c 2.0 2.0
3 d 4.0 8.0
4 f NaN NaN
我不知道这个方法存在,而且看起来更简单。谢谢你,伙计!呆在家里!
A B C
b 1.0 1.0
d 4.0 8.0
c 2.0 2.0
a 3.0 7.0
f NaN NaN
df1.set_index('A').combine_first(df2.set_index('A')).reset_index()
A B C
0 a 3.0 7.0
1 b 1.0 1.0
2 c 2.0 2.0
3 d 4.0 8.0
4 f NaN NaN