首页 > 解决方案 > 使用值列表从数据框中选择行

问题描述

我有一个值列表,我想用它来选择数据框中的行。诀窍是我想选择列表值在行中的任何行。例子:

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

标签: python-3.xpandasdataframe

解决方案


用于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

推荐阅读