Use a list of values to select rows from a Pandas dataframe Use a list of values to select rows from a Pandas dataframe python python

Use a list of values to select rows from a Pandas dataframe


You can use the isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})In [2]: dfOut[2]:   A  B0  5  11  6  22  3  33  4  5In [3]: df[df['A'].isin([3, 6])]Out[3]:   A  B1  6  22  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]Out[4]:   A  B0  5  13  4  5


You can use the method query:

df.query('A in [6, 3]')# df.query('A == [6, 3]')

or

lst = [6, 3]df.query('A in @lst')# df.query('A == @lst')


Another method;

df.loc[df.apply(lambda x: x.A in [3,6], axis=1)]

Unlike the isin method, this is particularly useful in determining if the list contains a function of the column A. For example, f(A) = 2*A - 5 as the function;

df.loc[df.apply(lambda x: 2*x.A-5 in [3,6], axis=1)]

It should be noted that this approach is slower than the isin method.


matomo