搜索词(不考虑搜索词的大小写)

2024-04-25 17:52:39 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码在整个数据帧中搜索字符串。你知道吗

df[df.apply(lambda x: x.astype(str).str.contains(search)).any(axis=1)]

然而,我有一个问题,它失败了,如果搜索小组是大写字母。是否有任何方法可以搜索整个数据帧,而不管数据帧中的搜索词是大写还是小写。你知道吗


Tags: 数据方法lambda字符串代码dfsearch小组
3条回答

使用applymap应用于数据帧的每个单元格。你知道吗

>>> df = pd.DataFrame({'x':['this','is'], 'y':['test', 'Hi']})
>>> search = 'HI'
>>> df.applymap(lambda x: search.lower() in x.lower())
       x      y
0   True  False
1  False   True

如果你每行都需要

>>> df.applymap(lambda x: search.lower() in x.lower()).any(axis=1)
0    True
1    True
dtype: bool

您可以使用:

df[df.applymap(str.lower).apply(lambda x: x.astype(str).str.contains(search)).any(axis=1)]

我相信对于忽略情况,需要参数flagsre.I

import re

df[df.apply(lambda x: x.astype(str).str.contains(search, flags=re.I)).any(axis=1)]

另一种解决方案是转换每一列和search字符串:

df[df.apply(lambda x: x.astype(str).str.lower().str.contains(search.lower())).any(axis=1)]

相关问题 更多 >