user18243nanana user18243nanana - 3 months ago 20
Python Question

How to slice pandas DataFrame by disjunction statement (logical "or")?

I would like to slice a

pandas.DataFrame
which satisfies condition A or condition B. Most of the search results only show how to slice dataframe using "and". So I wonder if it is possible to use "or" operator without converting (A and B) to (not (not A and not B))? Because sometimes there are many "or" conditions needed, and converting might be troublesome.

I tried to use:

df[(df['c1']==x1) or (df['c2']==x2)]


but it does not work.

Answer

You need to use the logical or symbol |

df[(df['c1'] == x1) | (df['c2'] == x2)]