Find all instances where a pandas dataframe containing a column of int's matches a dataframe with a column of a list of ints

Viewed 48

I have 2 dataframes. One (a) has a column of integers and one (b) has a column of a list of integers (array or list)

I'm trying to find a way to find all occurrences of b where b contains a.

I hoped something like this would work

df3 = a[a['cell'].isin(b['cells'])]

But I get an empty dataframe.

1 Answers

I tried using columns 'a' and 'b' in the same dataframe. Here is the filter that worked for me on an example dataframe I made.

data=pd.DataFrame([[1, [1, 2, 3]], [5, [11, 12, 13]], [6, [7, 6, 10]]], columns=['a', 'b'])
mask=(pd.Series(data.index)).apply(lambda x:(data.loc[x, ['a']]).isin(data.loc[x, ['b']].values[0]))

data:

enter image description here

data.loc[mask['a'].values]:

enter image description here

Related