0

I'm using the 2 optional codes to create a new column in my df and include the values wanted as well:

Option 1

cov19.loc[cov19['cases'] <= 10, 'estrats'] = 'Very Low' 
cov19.loc[cov19['cases'] > 10 and <= 50, 'estrats'] = 'Low' 
cov19.loc[cov19['cases'] > 50 and <= 100, 'estrats'] = 'Medium' 
cov19.loc[cov19['cases'] > 100 and <= 1000, 'estrats'] = 'High' 
cov19.loc[cov19['cases'] > 1000, 'estrats'] = 'Very High' 

Error returned 1:

cov19.loc[cov19['set_of_numbers'] > 10 and <= 50, 'estrats'] = 'Low'
                                            ^
SyntaxError: invalid syntax

Optional code 2

cov19.loc[cov19['cases'] <= 10, 'estrats'] = 'Very Low' 
cov19.loc[cov19['cases'] > 10 and cov19['cases'] <= 50, 'estrats'] = 'Low' 
cov19.loc[cov19['cases'] > 50 and cov19['cases'] <= 100, 'estrats'] = 'Medium' 
cov19.loc[cov19['cases'] > 100 and cov19['cases']<= 1000, 'estrats'] = 'High' 
cov19.loc[cov19['cases'] > 1000, 'estrats'] = 'Very High' 

Error returned 2

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

1 Answers1

2

This is what you would want:

cov19.loc[(cov19['cases'] > 10) & (cov19['cases'] <= 50), 'estrats'] = 'Low' 

& here does element-wise AND operation and you wrap the operands to it using parentheses.

Also, a bit more clarification about & vs and :

and is boolean operation where & is bitwise. So, when you want to compute the AND operation between individual components of the objects, use &

Partha Mandal
  • 1,391
  • 8
  • 14
  • Thanks @ParthaMandal, this is what I was looking for. Thanks also for your explanation! –  May 21 '20 at 12:05