Search code examples
pythonpandaslogical-and

Evaluation of Logical AND in pandas


I have dataframe Cities in pandas. I need to add a boolean column in it that is true if
1. The city is named after a saint.
2. The city has an area greater than 50 square miles.

I wrote below conditions for evaluating it.

cities['cond1'] = cities['City name'].str.contains('San') & cities['Area square miles'] > 50
cities['cond2'] = cities['Area square miles'] > 50 & cities['City name'].str.contains('San')
cities
for which i get below result:

City    name        Population    Area square miles  cond1        cond2  
 0   San Francisco  852469        46.87              False        True
 1   San Jose       1015785       176.53             False        True
 2   Sacramento     485199        97.92              False        True  

Both cond1 and cond2 columns check for same condition but give opposite results, which also seems incorrect as I am trying to do AND operation. Please help me in understanding this result and how can i correctly check for the above conditions.


Solution

  • As > is lower precedence than &, A > X & B is parsed as A > (X & B) but what you want is (A > X) & B.