MVMV
MVMV

Reputation: 37

Select dataframes rows based on an OR condition

I have a df dataframe with one column named "Move", and I want to keep only the rows for which Move is "Right" or "Left".

But this doesn't work:

df = df[df.Move == 'Right' or df.Move == 'Left']

neither does this:

moves = ['Right','Left']
df = df[df.Move in moves]

Would you have any idea of how to do something like that?

Upvotes: 1

Views: 639

Answers (2)

Nikhil Kumar
Nikhil Kumar

Reputation: 99

I think you are missing parenthesis, try using this

df = df.loc[(df.Move == "Right") & (df.Move == "Left")]

Upvotes: 2

Marcus Vinicius Pompeu
Marcus Vinicius Pompeu

Reputation: 1261

Welcome to the world of try and error of Pandas :-)

df = df[(df.Move == 'Right') | (df.Move == 'Left')]

The explanation TLDR;

  • Masks are boolean Series, hence, subject to bitwise operators OR |, AND & and NOT/XOR ^

An answer from StackOverflow: https://stackoverflow.com/a/64939034/206413

Edited: parenthesis for clauses

Upvotes: 1

Related Questions