1

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?

MVMV
  • 37
  • 6

2 Answers2

2

I think you are missing parenthesis, try using this

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

0

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

Marcus Vinicius Pompeu
  • 1,219
  • 1
  • 11
  • 24
  • Well, I tried this too, but it doesn't work either. It gives me : TypeError: Cannot perform 'ror_' with a dtyped [object] array and scalar of type [bool] – MVMV Jun 16 '21 at 02:29
  • 1
    I found my mistake. I needed parenthesis, so it works with df = df[(df.Move == 'Right') | (df.Move == 'Left')]. Thanks you for your help. – MVMV Jun 16 '21 at 02:34
  • @MVMV, yep, me too :-) I just edited my answer adding the parenthesis, after fiddling in the jupyter notebook :-) I hope you upvote my answer. I'm almost at 1000 points! Please, please, please... – Marcus Vinicius Pompeu Jun 16 '21 at 02:36
  • I tried to upvote it, but the site tells me that I need at least 15 reputation to cast a vote or something. Maybe I can't do it because I just arrived on stakcoverflow? I'm definitely coming back to this post to upvote your answer as soon as I get 15 reputation, don't worry :) – MVMV Jun 16 '21 at 02:44
  • @MVMV, thanks for trying! Thanks, thanks, thanks! I was in the same position years ago and now I try to reach 1000 points. Hope to help you reach 1000 points some time in the future :-) Enjoy the ride. – Marcus Vinicius Pompeu Jun 16 '21 at 02:47