fly*_*all 18 python dataframe pandas
我正在尝试一次更新几个字段 - 我有两个数据源,我正在尝试协调它们.我知道我可以做一些丑陋的合并,然后删除列,但希望下面的代码工作:
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
Run Code Online (Sandbox Code Playgroud)
我想要的输出是:
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
Run Code Online (Sandbox Code Playgroud)
我打赌它与切片上的更新/设置有关,但我总是使用.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
Run Code Online (Sandbox Code Playgroud)
请注意,我没有在这里考虑索引,我过滤到2x1系列并将其设置为等于4x1系列,但它正确处理它.思考?我试图更好地理解我已经使用了一段时间的功能,但我想我没有完全掌握底层机制/规则
piR*_*red 19
你想要替换
print df.loc[df['Col1'].isnull(),['Col1','Col2', 'Col3']]
Col1 Col2 Col3
2 NaN NaN NaN
3 NaN NaN NaN
Run Code Online (Sandbox Code Playgroud)
附:
replace_with_this = df.loc[df['Col1'].isnull(),['col1_v2','col2_v2', 'col3_v2']]
print replace_with_this
col1_v2 col2_v2 col3_v2
2 a b d
3 d e f
Run Code Online (Sandbox Code Playgroud)
似乎合理.但是,在执行分配时,需要考虑索引对齐,其中包括列.
所以,这应该工作:
df.loc[df['Col1'].isnull(),['Col1','Col2', 'Col3']] = replace_with_this.values
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 b d a b d
3 d e f d e f
Run Code Online (Sandbox Code Playgroud)
我通过最后使用来计算列数.values.这剥离了replace_with_this数据框中的列信息,只是在适当的位置使用了这些值.
| 归档时间: |
|
| 查看次数: |
19694 次 |
| 最近记录: |