3

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.

2 Answers 2

4

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.)

2
  • just want to chime in to mention that df.query("x in {}".format(my_list)) has worked for me in the past (in the case when retyping the valid values is too cumbersome)
    – Paul H
    Feb 26, 2015 at 17:14
  • 1
    @PaulH: for that, you can use df.query("Y in @my_list") instead of building a string.
    – DSM
    Feb 26, 2015 at 17:15
2

Yes, there is: pandas.DataFrame.isin.

df_update = df[(df.X == 1) & df.Y.isin(['A', 'B', 'C'])]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.