首页 > 解决方案 > 将列中的熊猫列表与外部列表进行比较

问题描述

给定一个示例数据框列:

colA           colB
1              [20,40,50,60]
2              [20,70,80]
3              [10,90,100]

并给出这个列表 test_lst = [20, 45, 35]

我正在尝试开发一种方法来过滤我的数据框以仅显示其中列表中至少一个值colBtest_lst

尝试了几种技术。最新的是这个:

df[any(x in df['colB'] for x in test_lst)]

我相信这里的一些 Pandas/Python 专家已经准备好了。感谢您花时间检查这个谜(至少对我来说是一个谜)。

标签: pythonpandas

解决方案


您可以使用set.intersection

test_lst = [20, 45, 35]
print(df[df.colB.apply(lambda x: set(x).intersection(test_lst)).astype(bool)])

印刷:

   colA              colB
0     1  [20, 40, 50, 60]
1     2      [20, 70, 80]

推荐阅读