我有一个3列pandas数据帧,即: col1,col2,col3
我想将col1的数据帧更新为col col,其中col 3 = 0
以下代码使更新成功,但它发出了关于在切片副本上设置值的警告
df.col1.loc[df.col3==0] = df.col2.loc[df.col3==0]
修改代码以删除警告的任何方法?
答案 0 :(得分:1)
#cache to variable
mask = df.col3 == 0
df.loc[mask, 'col1'] = df.loc[mask, 'col2']
还有另一种可能的方法 - mask
或numpy.where
:
df['col1'] = df['col1'].mask(mask, df['col2'])
df['col1'] = np.where(mask, df['col2'], df['col1'])