如果我想在Pandas中使用以下语法来使用比较运算符创建if
条件,是否需要将or
条件包装在其自己的括号内?
没有多余的括号
df.loc[(df['Col1'] == 'Yes') &
(df['Col2'] == 'Yes') &
(df['Col3'] == 'No') |
(df['Col3'] == 'Yes') |
(df['Col3'] == 'Maybe'),
['Result']] = 'CORRECT'
带有额外的括号
df.loc[(df['Col1'] == 'Yes') &
(df['Col2'] == 'Yes') &
((df['Col3'] == 'No') |
(df['Col3'] == 'Yes') |
(df['Col3'] == 'Maybe')),
['Result']] = 'CORRECT'
还是都有效?很难从正确的文档中得出结论。
答案 0 :(得分:2)
我认为最好使用isin
:
df.loc[(df['Col1'] == 'Yes') &
(df['Col2'] == 'Yes') &
(df['Col3'].isin(['No', 'Yes', 'Maybe'])), 'Result'] = 'CORRECT'
但是您的陈述是不同的:
@DeepSpace-评论:
它与熊猫没有直接关系,但与operator precedence in Python无关。按位和(&)优先于按位或(|),因此在这种情况下需要括号。
np.random.seed(1245)
a = ['No', 'Yes', 'Maybe']
df = pd.DataFrame(np.random.choice(a, size=(10, 3)), columns=['Col1','Col2','Col3'])
df.loc[(df['Col1'] == 'Yes') &
(df['Col2'] == 'Yes') &
(df['Col3'] == 'No') |
(df['Col3'] == 'Yes') |
(df['Col3'] == 'Maybe'),
'Result1'] = 'CORRECT'
df.loc[(df['Col1'] == 'Yes') &
(df['Col2'] == 'Yes') &
((df['Col3'] == 'No') |
(df['Col3'] == 'Yes') |
(df['Col3'] == 'Maybe')),
'Result2'] = 'CORRECT'
df.loc[(df['Col1'] == 'Yes') &
(df['Col2'] == 'Yes') &
(df['Col3'].isin(['No', 'Yes', 'Maybe'])), 'Result3'] = 'CORRECT'
print (df)
Col1 Col2 Col3 Result1 Result2 Result3
0 Maybe Yes Yes CORRECT NaN NaN
1 No Maybe No NaN NaN NaN
2 Yes No Maybe CORRECT NaN NaN
3 Maybe Yes No NaN NaN NaN
4 Yes Yes Maybe CORRECT CORRECT CORRECT
5 Yes Maybe Yes CORRECT NaN NaN
6 Maybe Maybe Yes CORRECT NaN NaN
7 Maybe No Yes CORRECT NaN NaN
8 Maybe Maybe Maybe CORRECT NaN NaN
9 Yes Yes No CORRECT CORRECT CORRECT