William Baker Morrison
William Baker Morrison

Reputation: 1789

Using "or" in pandas dataframe to search for strings

I would like to do this:

df[(df["Class"] == 'Class1' or  'Class2')]

i.e. find rows with class 1 or 2, but can't find the correct syntax in the documentation.

Upvotes: 0

Views: 67

Answers (2)

jezrael
jezrael

Reputation: 862611

Better is use isin:

df[df["Class"].isin(['Class1','Class2'])]

Or use | for bitwise or with () because priority precedence of operators with boolean indexing:

df[(df["Class"] == 'Class1') |  (df["Class"] == 'Class2')]

Another solutions with query:

df.query("Class == ['Class1', 'Class2']")

Or:

df.query("Class == 'Class1' |  Class == 'Class2'")
#here working or too
#df = df.query("Class == 'Class1' or  Class == 'Class2'")

Upvotes: 3

rpanai
rpanai

Reputation: 13437

These are the options

df[(df["Class"] == 'Class1') |  (df["Class"] =='Class2')]

or

df[df["Class"].isin(['Class1','Class2'])]

Upvotes: 0

Related Questions