本文介绍了 pandas :如果满足3列中的条件,则更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数据框:
I have a dataframe like this:
In[1]: df Out[1]: A B C D 1 blue red square NaN 2 orange yellow circle NaN 3 black grey circle NaN,并且我想在D列满足3个条件时进行更新.例如:
and I want to update column D when it meets 3 conditions. Ex:
df.ix[ np.logical_and(df.A=='blue', df.B=='red', df.C=='square'), ['D'] ] = 'succeed'它适用于前两个条件,但不适用于第三个条件,因此:
It works for the first two conditions, but it doesn't work for the third, thus:
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实现这一目标的更好方法似乎是:
A better way of achieving this seems to be:
df.loc[(df['A'] == 'blue') & (df['B'] == 'red') & (df['C'] == 'square'),'D'] = 'M5'更多推荐
pandas :如果满足3列中的条件,则更新值
发布评论