AND OR PANDAS CONDITION

Asked

Viewed 166 times

0

I have a question to configure the filters "e" and "ou" in the pandas.

Example: A column with the following col1 values (yes, no, maybe)

to get the yes OK

df[df['col1']=='sim']

Now, to catch:

yes or no

yes and no

yes and yes

How would you do?

2 answers

1

You can use the operator | to define the OR operation, or the operator & for operation E.

df[df['col1'] == 'sim' | df['col1'] == 'nao']  # Retorna se for "sim" ou "nao"
df[df['col1'] == 'sim' & df['col1'] == 'nao']  # Retorna se for "sim" e "nao" (nunca)

In OR, you can simplify using the method isin:

df[df['col1'].isin(['sim', 'nao'])]  # Retorna se for "sim" ou "nao"

0

A more intuitive way to do this is by using the query command, but in terms of performance is not as fast as a pandas' isin:

Yes or No

df.query("col1 == 'sim' or col1 == 'nao'")

Yes and No / this never happens

df.query("col1 == 'sim' and col1 == 'nao'")

Yes or Yes / ambiguous

df.query("col1 == 'sim' and col1 == 'sim'")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.