Victor
Victor

Reputation: 17097

Pandas logical operator & does not work but 'and' works

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.

Upvotes: 0

Views: 1986

Answers (1)

Toby Petty
Toby Petty

Reputation: 4660

& 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

Upvotes: 3

Related Questions