我有这样的数据帧:
In[1]: df
Out[1]:
A B C D
1 blue red square NaN
2 orange yellow circle NaN
3 black grey circle NaN
我想在满足3个条件时更新D列.例如:
df.ix[ np.logical_and(df.A=='blue', df.B=='red', df.C=='square'), ['D'] ] = 'succeed'
它适用于前两个条件,但它不适用于第三个条件,因此:
df.ix[ np.logical_and(df.A=='blue', df.B=='red', df.C=='triangle'), ['D'] ] = 'succeed'
有完全相同的结果:
In[1]: df
Out[1]:
A B C D
1 blue red square succeed
2 orange yellow circle NaN
3 black grey circle NaN
解决方法:
使用:
df[ (df.A=='blue') & (df.B=='red') & (df.C=='square') ]['D'] = 'succeed'
发出警告:
/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py:2: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
实现这一目标的更好方法似乎是:
df.loc[(df['A'] == 'blue') & (df['B'] == 'red') & (df['B'] == 'square'),'label'] = 'M5'
标签:python,pandas
来源: https://codeday.me/bug/20191004/1852407.html