0

I am having problem with logical operators in pandas. If I try :

list1=['x','y']
if st1=='A' & str2 not in list1: #do stuff

I get:

unsupported operand type(s) for &: 'str' and 'bool'", u'occurred at index 0

But this works: Why?

if st1=='A' and str2 not in list1: #do stuff

All I did was change & to and.

Victor
  • 16,609
  • 71
  • 229
  • 409

1 Answers1

3

& and and are not the same thing in Python - & is a bitwise operator, and is a logical operator. See previous answers here and here, and Wikipedia page on bitwise operations.

In pandas you can use & for logical operations when selecting subsets of DataFrames, e.g.:

df = pd.DataFrame(data={"col1":[1,2,3], "col2":[2,3,4]})
df[(df["col1"]>1) & (df["col2"]<4)] # Selects second row based on boolean criteria
Toby Petty
  • 4,431
  • 1
  • 17
  • 29