我正在尝试一次更新几个字段 - 我有两个数据源,我正在尝试调和它们。我知道我可以做一些丑陋的合并,然后删除列,但期望下面的代码工作:
df = pd.DataFrame([['A','B','C',np.nan,np.nan,np.nan],
['D','E','F',np.nan,np.nan,np.nan],[np.nan,np.nan,np.nan,'a','b','d'],
[np.nan,np.nan,np.nan,'d','e','f']], columns = ['Col1','Col2','Col3','col1_v2','col2_v2','col3_v2'])
print df
Col1 Col2 Col3 col1_v2 col2_v2 col3_v2
0 A B C NaN NaN NaN
1 D E F NaN NaN NaN
2 NaN NaN NaN a b d
3 NaN NaN NaN d e f
#update
df.loc[df['Col1'].isnull(),['Col1','Col2', 'Col3']] = df[['col1_v2','col2_v2','col3_v2']]
print df
Col1 Col2 Col3 col1_v2 col2_v2 col3_v2
0 A B C NaN NaN NaN
1 D E F NaN NaN NaN
2 NaN NaN NaN a b d
3 NaN NaN NaN d e f
我想要的输出是:
Col1 Col2 Col3 col1_v2 col2_v2 col3_v2
0 A B C NaN NaN NaN
1 D E F NaN NaN NaN
2 a b c a b d
3 d e f d e f
我认为它与切片上的更新/设置有关,但我总是使用.loc更新值,而不是一次更多的列。
我觉得有一种简单的方法可以做到这一点,我只是想念,任何想法/建议都会受到欢迎!
编辑以反映以下解决方案 感谢您对索引的评论。但是,我对此有一个疑问,因为它与系列有关。如果我想以类似的方式更新单个系列,我可以这样做:
df.loc[df['Col1'].isnull(),['Col1']] = df['col1_v2']
print df
Col1 Col2 Col3 col1_v2 col2_v2 col3_v2
0 A B C NaN NaN NaN
1 D E F NaN NaN NaN
2 a NaN NaN a b d
3 d NaN NaN d e f
请注意,我没有在这里考虑索引,我过滤到2x1系列并将其设置为等于4x1系列,但它正确处理了它。思考?我试图更好地理解我已经使用了一段时间的功能,但我想我没有完全掌握底层机制/规则