Python 熊猫:如果满足 3 列中的条件,则更新值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21263020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas : update value if condition in 3 columns are met
提问by Eduardo Oliveira
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
and I want to update column D when it meets 3 conditions. Ex:
我想在满足 3 个条件时更新列 D。前任:
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'
has exactly the same result:
有完全相同的结果:
In[1]: df
Out[1]:
A B C D
1 blue red square succeed
2 orange yellow circle NaN
3 black grey circle NaN
回答by Tim
You could try this instead:
你可以试试这个:
df[ (df.A=='blue') & (df.B=='red') & (df.C=='square') ]['D'] = 'succeed'
回答by waitingkuo
The third parameter of logical_andis to assign the array used to store the result.
logical_and的第三个参数是分配用于存储结果的数组。
Currently, the method @TimRich provided might be the best. In pandas 0.13 (in development), there's a new experimental querymethod. Try it!
目前,@TimRich 提供的方法可能是最好的。在 pandas 0.13(开发中)中,有一种新的实验性查询方法。尝试一下!
回答by Praveen
Using:
使用:
df[ (df.A=='blue') & (df.B=='red') & (df.C=='square') ]['D'] = 'succeed'
gives the warning:
给出警告:
/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'
回答by theSanjeev
You could try:
你可以试试:
df['D'] = np.where((df.A=='blue') & (df.B=='red') & (df.C=='square'), 'succeed')
This answer might provide a detailed answer to the your question: Update row values where certain condition is met in pandas
此答案可能会为您的问题提供详细的答案: 在熊猫中满足特定条件时更新行值
回答by Alex Schwab
This format might have been implied in the new answers, but the following bit actually worked for me.
新答案中可能暗示了这种格式,但以下内容实际上对我有用。
df['D'].loc[(df['A'] == 'blue') & (df['B'] == 'red') & (df['C'] == 'square')] = 'succeed'
df['D'].loc[(df['A'] == 'blue') & (df['B'] == 'red') & (df['C'] == 'square')] = 'succeed'

