Python pandas 在另一列的元素列表中查找一列的元素

Python pandas find element of one column in list of elements of another column

这是我的问题,我想在数据框 B 列的元素列表中找到 A 列的元素。因此,我只想保留那些在 A 中找到元素的行:

df = pd.DataFrame({'A': [1, 2],
                   'B': [1, 3]
                 })
result = df[df.A.isin(df.B)]

>>> result
   A  B
0  1  1

工作正常,但我真正想要的是:

df = pd.DataFrame({'A': [1, 2],
                   'B': [[1, 2], [1, 3]]
                 })
result = df[df.A.isin(df.B)]

>>> result
Empty DataFrame
Columns: [A, B]
Index: []

哪个不起作用,因为 A 中的元素不是与 B 列中列表的元素进行比较,而是与整个列表进行比较?

我想要的结果是:

>>> result
   A       B
0  1  [1, 2]

这可能吗?

你可以做到 apply:

df[df.apply(lambda row: row['A'] in row['B'], axis=1)]

或 zip 理解:

df[[a in b for a,b in zip(df['A'], df['B'])]]

输出:

   A       B
0  1  [1, 2]