python - 将列中的熊猫列表与外部列表进行比较
问题描述
给定一个示例数据框列:
colA colB
1 [20,40,50,60]
2 [20,70,80]
3 [10,90,100]
并给出这个列表 test_lst = [20, 45, 35]
我正在尝试开发一种方法来过滤我的数据框以仅显示其中列表中至少一个值colB
在test_lst
尝试了几种技术。最新的是这个:
df[any(x in df['colB'] for x in test_lst)]
我相信这里的一些 Pandas/Python 专家已经准备好了。感谢您花时间检查这个谜(至少对我来说是一个谜)。
解决方案
您可以使用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]
推荐阅读
- javascript - Rxjs - 如何在 combinelatest 之后调用两个 httpService?
- python - 在 Python 中编写 Discord 机器人 - 如何使机器人将命令限制到某个服务器?
- visual-studio - 调试找不到着陆页
- python - 如何将字符串类型列表更改为列表类型,然后删除 nan 元素
- javascript - 当该字段是外键时,如何使用 OR 条件进行查询
- postgresql - postgres 无法创建复制槽
- python - 如何使用python打开文件,将行拆分为列表,然后在第三个列表中搜索具有最高值的行
- c - 使用枚举修改 C 中的打印语句
- ruby-on-rails - 如何在移动性中使用语言环境或失败访问器验证翻译?
- python - Python中的最佳拟合线不准确