0

Can logical operators be used in Pandas' df.loc?

In this generic example of dataframe with numbers, I'm trying to create a column that signalizes whether the cell in the previous column has a 4 or a 6.

numbers = {'set_of_numbers': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(numbers,columns=['set_of_numbers'])

df.loc[df['set_of_numbers'] = 4 or df['set_of_numbers'] = 6, 'four_or_six'] = 'True' 
df.loc[df['set_of_numbers'] != 4 and df['set_of_numbers'] != 6, 'four_or_six'] = 'False'

The output is "invalid syntax". Why?

Incognito
  • 331
  • 1
  • 5
  • 14
  • `|` for `or`, `&` for `and`. Don't forget parenthesis around comparisons – Psidom Jul 02 '20 at 20:47
  • Don't need Loc, try this: `df['four_or_six'] = df['set_of_numbers'].isin([4, 6])` – cs95 Jul 02 '20 at 20:49
  • I tried this, but syntax is still invalid: df2.loc[(df2['set_of_numbers'] = 4) | (df2['set_of_numbers'] = 6), 'four_or_six'] = 'True' df2.loc[(df2['set_of_numbers'] != 4) & (df2['set_of_numbers'] != 6), 'four_or_six'] = 'False' – Incognito Jul 02 '20 at 21:06

0 Answers0