首页 > 解决方案 > 从包含子字符串的数据框列表中提取数据框

问题描述

我在 python 中有以下数据框,它们是列表的一部分

dataframe_list= []## CREATE AN EMPTY LIST
import pandas as pd
A=pd.DataFrame()
A["name"]=["A", "A", "A"]
A["att"]=["New World", "Hello", "Big Day now"]
B=pd.DataFrame()
B["name"]=["A2", "A2", "A2"]
B["Col"]=["L", "B", "B"]
B["CC"]=["old", "Hello", "Big Day now"]
C=pd.DataFrame()
C["name"]=["Brave old World", "A", "A"]

上述数据帧的大小不同。这些存储为如下列表

 dataframe_list.append(A)
 dataframe_list.append(B)
 dataframe_list.append(C)

我正在尝试提取两个包含单词 world 的数据框(无论大小写)。我试过下面的代码

list1=["World"]
result=[x for x in dataframe_list if any(x.isin(list1) ) ]

然而,这会产生所有数据帧。预期的输出是数据帧A,C。我不确定我在哪里犯了错误

标签: pandasdataframestring-matching

解决方案


使用DataFrame.stackforSeries和 test by Series.str.containswordw代替一个元素列表,还添加了单词边界以仅匹配整个单词:

w="World"
result=[x for x in dataframe_list if x.stack().str.contains(rf"\b{w}\b", case=False).any()]
print (result)
[  name          att
0    A    New World
1    A        Hello
2    A  Big Day now,               name
0  Brave old World
1                A
2                A]

编辑:对于单词列表|用于正则表达式或:

list1=["World",'Hello']
pat = '|'.join(rf"\b{x}\b" for x in list1)
result=[x for x in dataframe_list if x.stack().str.contains(pat, case=False).any()]

推荐阅读