If one of the column value match with another array return the dataframe of unique id with all of it's rows

Viewed 53
 df=
    id - val1
    1  -  50
    2  -  40
    1  -  60
    2  -  41

a = [50]

output = id - val1
         1  -  50
         1  -  60

Suppose i have a panda dataframe like df and a array like 'a'. Now if any of the value of val1 column of df column match with this array i want to return all the entry of unique id (like output). How can i do this?

2 Answers

You can use groupby.transform with isin and any:

df[df.groupby('id')['val1'].transform(lambda x: x.isin(a).any())]

or alternatively, nested isin:

df.loc[df['id'].isin(df.loc[df['val1'].isin(a), 'id'])]

[out]

   id  val1
0   1    50
2   1    60

You could use groupby's filter and any to get the unique ids that match a:

 a = [50]

 df.groupby('id').filter(lambda x: x.val1.isin(a).any())

    id  val1
0   1   50
2   1   60
Related