python-3.x - 使用值列表从数据框中选择行
问题描述
我有一个值列表,我想用它来选择数据框中的行。诀窍是我想选择列表值在行中的任何行。例子:
index color shape
1 blue star
2 red square
3 yellow circle
我的清单是
list_vals = ['sq', 'blu']
我想选择行
index color shape
1 blue star
2 red square
解决方案
用于DataFrame.stack
转换为Series
,然后用于Series.str.contains
查找您感兴趣的字符串 - 我们将用于'|'.join
创建一个正则表达式“或”模式,将 中的所有项目组合在一起list_items
。
'sq|blu'
作为参考,这个正则表达式模式在这种情况下看起来像。
接下来,Series.unstack
要恢复原始形状并使用DataFrame.any
轴 1 创建布尔索引,我们将使用它来返回所需的行。
df[df.stack().str.contains('|'.join(list_vals)).unstack().any(1)]
[出去]
ndex color shape
0 1 blue star
1 2 red square
推荐阅读
- spring-cloud-stream - 如何启用具有两个不同输入主题的函数路由
- javascript - 当有人说话时发送图像
- python - 具有多个输出的熊猫旋转数据框
- jquery - jquery在对话框中更改按钮文本颜色
- angular - 如何在 ng build --watch 上设置 HMR 并自动重新加载 URL?
- bash - 在 bash 中创建文件的备份
- nginx - 如何代理将目录列表的请求传递到另一台服务器(Nginx)
- python - Python 跳到另一个 csv 行
- reactjs - 异常处理没有从 redux action catch 块中完成?
- wordpress - 如何在 WP_Query 中使用数组作为 meta_key?