Boolean subset in pandas
pandas, python
Solution
You could use `isin`, or the new `query` syntax:
>>> df = pd.DataFrame({"X": [1,1,2,1,1], "Y": ["A","D","B","C", "D"]})
>>> df[(df.X == 1) & df.Y.isin(["A","B","C"])]
X Y
0 1 A
3 1 C
>>> df.query("X == 1 and Y in ['A','B','C']")
X Y
0 1 A
3 1 C
`isin` is likely to be faster, especially for small frames; `query` can sometimes be more convenient (and can sometimes be faster for really large frames.)
Problem
I want to subset a data frame with pandas in python. Currently I am using ``` df_update = df[(df.X == 1) & ((df.Y == 'A') | (df.Y == 'B') | (df.Y == 'C'))] ``` Is there a way to reduce the code to something like: ``` df_update = df[(df.X == 1) & (df.Y in ['A', 'B', 'C'])] ``` Great thanks in advance.