2

I'm looking at this example from the documentation:

df.loc[lambda df: df['shield']==8]

How do I extend this with an OR condition? I'm trying to do this but it doesn't work:

df.loc[lambda df: df['shield']==8 or df['max_speed'] ==1]

Also, as a side note, what is the point of the lambda function in this case since:

 df.loc[df['shield']==8]

works just fine.

Henry Ecker
  • 31,792
  • 14
  • 29
  • 50
Noobcoder
  • 163
  • 1
  • 12
  • 1
    Definitely don't use functions to index for this, they are quite pointless here. Also you should be chaining the conditions with [bitwise operators](https://wiki.python.org/moin/BitwiseOperators). Check [this answer](https://stackoverflow.com/questions/13611065/efficient-way-to-apply-multiple-filters-to-pandas-dataframe-or-series) for more details – yatu Apr 16 '20 at 12:49

1 Answers1

1

Because working with arrays, here Series is necessary use butwise OR by | and because priority of operators is necessary add parentheses:

df.loc[lambda df: (df['shield']==8) | (df['max_speed'] ==1)]
jezrael
  • 729,927
  • 78
  • 1,141
  • 1,090
  • Thanks. Also, I've never used bitwise operators before. Is it a quirk when working with pandas? Why didn't it just an "or" and "and"? – Noobcoder Apr 16 '20 at 13:05
  • 1
    @Noobcoder - Exactly you are right, it is like `or` for arrays is `|`, `&` for `AND` and `~` for NOT. This operarors also working in numpy (and pandas too, because pandas built on numpy). – jezrael Apr 16 '20 at 13:07