Python 3.x 使用值列表从数据帧中选择行

Python 3.x 使用值列表从数据帧中选择行,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,我有一个值列表,可以用来选择数据框中的行。诀窍是我想选择列表值所在的任何行。例如: 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 使

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

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
使用转换为
系列
,然后使用查找您感兴趣的字符串-我们将使用
“|”。加入
创建一个正则表达式或“模式”,将
列表中的所有项目组合起来

作为参考,在本例中,此正则表达式模式类似于
'sq | blu'

接下来,要返回原始形状并使用轴1创建布尔索引,我们将使用它返回所需的行

df[df.stack().str.contains('|'.join(list_vals)).unstack().any(1)]
[外]

这里有一种方法

df_filtered = (
    df[(df['color'].str.contains(list_vals[0])) |
        (df['shape'].str.contains(list_vals[1]))
        ]
                )

print(df_filtered)
   index color   shape
0      1  blue    star
1      2   red  square
编辑

另一种方法基于(包含对该方法的完整解释)

  • 我所做的唯一更改是(1)将您的搜索列表加入到单个搜索字符串中,(2)返回搜索(筛选)结果的
    数据框
    (行)索引(然后使用该索引对原始
    数据框
输出

  color   shape
1   red  square

或者用管道连接列表,并在df上用
str.contains()
检查:

df[df.apply(lambda x: x.str.contains('|'.join(list_vals))).any(axis=1)]


你能解释一下你是如何选择索引3的吗?行似乎不包含
列表中所需的搜索词。我想他在这种情况下指的是索引1是的,对不起,没有引起足够的注意。我对选择索引1和索引2感兴趣。我已经对原始帖子进行了编辑。@MorganGladden,没问题。谢谢你的编辑!
df[df['shape'].apply(lambda x: any(s in x[:len(s)] for s in list_vals))]
  color   shape
1   red  square
df[df.apply(lambda x: x.str.contains('|'.join(list_vals))).any(axis=1)]
       color   shape
index              
1      blue    star
2       red  square