整行中的pandas数据框搜索字符串

标签 pandas dataframe search

我有一个如下所示的 Pandas 数据框。我想在数据框的每一行中搜索一个文本,并突出显示该文本是否出现在该行中。

例如,我想在每一行中搜索“jones”。我想忽略我的搜索词的大小写。在下面的情况下,我想向名为“jones”的数据添加一个新列,它的值为 1,1,0,因为在第一行和第二行中找到了该词

我找到了 this显示如何在列中查找文本的帖子,但是当我有很多列时如何找到文本 - 比如说 50+?我考虑过连接所有列并创建一个新列,但没有看到任何可以连接数据框所有列的函数(不要求输入每个列名)

我想为我拥有的多个关键字执行此操作。例如,我有关键字列表 LLC, Co, Blue, alpha还有更多(30+)

sales = [{'account': 'Jones LLC', 'Jan': '150', 'Feb': '200', 'Mar': '140'},
         {'account': 'Alpha Co',  'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
         {'account': 'Blue Inc',  'Jan': '50',  'Feb': '90',  'Mar': '95' }]
df = pd.DataFrame(sales)

来源DF:
   Feb    Jan  Mar    account
0  200    150  140  Jones LLC
1  210  Jones  215   Alpha Co
2   90     50   95   Blue Inc

期望的DF:
   Feb    Jan  Mar    account  jones  llc  co  blue  alpha
0  200    150  140  Jones LLC      1    1   0     0      0
1  210  Jones  215   Alpha Co      1    0   1     0      1
2   90     50   95   Blue Inc      0    0   0     1      0

最佳答案

这里我们使用内置的pandas str功能 contains ,以及 apply然后用 any 把它们放在一起如下,

search_string = 'Jones'

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

Out[2]:
     Feb    Jan    Mar   account     Jones
0    200    150    140   Jones LLC   1
1    210    Jones  215   Alpha Co    1
2    90     50     95    Blue Inc    0

这可以很容易地扩展为 contains使用正则表达式进行匹配。它还有一个 case arg,这样你就可以让它不区分大小写并搜索 Jonesjones .

为了遍历搜索词列表,我们需要进行以下更改。通过将每个搜索结果(一个 Series)存储在一个列表中,我们使用该列表将系列连接在一起成为 DataFrame .我们这样做是因为我们不想为新的 search_string 搜索新列,
df_list = []

for search_string in ['Jones', 'Co', 'Alpha']:
    #use above method but rename the series instead of setting to
    # a columns. The append to a list.
    df_list.append(df.apply(lambda x: x.str.contains(search_string))
                     .any(axis=1)
                     .astype(int)
                     .rename(search_string))

#concatenate the list of series into a DataFrame with the original df
df = pd.concat([df] + df_list, axis=1)
df

Out[5]:
    Feb    Jan     Mar    account    Jones  Co   Alpha
0   200    150     140    Jones LLC  1      0    0
1   210    Jones   215    Alpha Co   1      1    1
2   90     50      95     Blue Inc   0      0    0

关于整行中的pandas数据框搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48330608/

相关文章:

python - 在 python 中使用 np.where 函数时如何避免 NaN?

python - 基于两列值相等的 Pandas 将列中的字段设置为 0

python - 如何在 pandas 数据框中指定列类型

Pandas 数据框将列类型转换为字符串或分类

ruby-on-rails - 如何强制Rails查询为每个结果返回两个可能的模型?

python - 在 Pandas 数据框中使用 pyproj 在投影之间进行转换

python-3.x - 类型错误 : conversion from Series to Decimal is not supported

python - 如何将多个json文件读取到pandas dataframe中?

Delphi 搜索编辑组件

asp.net - Kentico CMS 搜索结果