pandas - 从包含子字符串的数据框列表中提取数据框
问题描述
我在 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。我不确定我在哪里犯了错误
解决方案
使用DataFrame.stack
forSeries
和 test by Series.str.contains
wordw
代替一个元素列表,还添加了单词边界以仅匹配整个单词:
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()]
推荐阅读
- java - 微服务 - 如何使用授权服务器和资源服务器对注册流程进行建模?
- c++ - 如何更改此插入函数以使用字符串在链表中工作?
- java - Android videoview - 沉浸式 - 重叠控制器
- c# - X509Certificate2 的 RawData 与 Export(X509ContentType.Cert) 有什么区别?
- webrtc - WebRtc 信令服务器可以在没有额外 STUN 服务器的情况下为客户端找到 ICE 候选者吗
- java - 无法自定义flowers_tf_lite.ipynb colab 中的_URL
- mysql - 利息查询日期减去总付款日期
- excel - 为什么我的使用 VBA 抓取文本的代码仅在调试中有效
- ios - 如何在应用程序后台循环调用 Rest web 服务?
- python - 如何使用 python 获取所有 Windows/Linux 用户,而不仅仅是当前用户