Allende
Allende

Reputation: 1482

Pandas filter rows based on values within a list

Given the df

df=pd.DataFrame([[0.23,"A1",10],[5.36,"A2",55],[8.8,"A3",4]],
            index=list('pqr'),
            columns=list('abc'))

And the following list

lst = ['A30','A50','A2','A0']

I would like to print the rows from the DF which values matches any of the values within the list, for the df and list above I would expect the output to be something like

Out[169]: 
    a    b   c
q  5.36  A2  55

But the closest I've got is this

mask=df.isin(lst)
df[mask].dropna(axis=0,how="all")
Out[170]: 
    a   b   c
q NaN  A2 NaN

The 'NaN' are result of doing "df[mask]" but I don't understand why neither if I'm doing right to get the output I want to.

Is there a way to achieve the output sample I mentioned above/next ?

Out[169]: 
    a    b   c
q  5.36  A2  55

Upvotes: 2

Views: 308

Answers (2)

cs95
cs95

Reputation: 402323

Just apply any on the result of isin.

df[df.isin(lst).any(axis=1)]

      a   b   c
q  5.36  A2  55

I've written more about this in How to implement 'in' and 'not in' for Pandas dataframe under the "Filter on MANY Columns" section.

Upvotes: 4

Yuca
Yuca

Reputation: 6091

Using list comprehension:

[print(x) for x in [df[df[col].isin(lst)] for col in list(df)] if len(x)>0]

Output:

      a   b   c
q  5.36  A2  55

Upvotes: 3

Related Questions