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

问题描述 投票:4回答:2

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

例如,我想在每一行中搜索“琼斯”。我想忽略搜索词的大小写。在以下情况下,我想向名为“ 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 dataframe search
2个回答
2
投票

[在这里,我们将熊猫内置的str函数containsapply一起使用,然后将它们全部与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使用正则表达式进行匹配。它还有一个大小写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

2
投票

UPDATE:您似乎想要OneHotEncode一些特定的单词-您可以使用sklearn.feature_extraction.text.CountVectorizer

In [131]: from sklearn.feature_extraction.text import CountVectorizer

In [132]: vocab = ['jones', 'llc', 'co', 'blue', 'alpha']

In [133]: cv = CountVectorizer(vocabulary=vocab)

In [134]: r = pd.SparseDataFrame((cv.fit_transform(df.select_dtypes('object').add(' ').sum(1)) != 0) * 1,
                                 df.index, 
                                 cv.get_feature_names(), 
                                 default_fill_value=0)

In [135]: r
Out[135]:
   jones  llc  co  blue  alpha
0      1    1   0     0      0
1      1    0   1     0      1
2      0    0   0     1      0

您也可以将其与原始DF合并:

In [137]: df = df.join(r)

In [138]: df
Out[138]:
   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

说明:

使用空格作为分隔符将所有字符串列连接为一个单独的列:

In [165]: df.select_dtypes('object').add(' ').sum(1)
Out[165]:
0    200 150 140 Jones LLC LLC
1       210 Jones 215 Alpha Co
2            90 50 95 Blue Inc
dtype: object

生成具有选定特征的One Hot Encode稀疏矩阵:

In [176]: A = (cv.fit_transform(df.select_dtypes('object').add(' ').sum(1)) != 0) * 1

In [177]: A
Out[177]:
<3x5 sparse matrix of type '<class 'numpy.int32'>'
        with 6 stored elements in Compressed Sparse Row format>

In [178]: A.A
Out[178]:
array([[1, 1, 0, 0, 0],
       [1, 0, 1, 0, 1],
       [0, 0, 0, 1, 0]])

In [179]: cv.get_feature_names()
Out[179]: ['jones', 'llc', 'co', 'blue', 'alpha']

从中生成一个SparseDataFrame:

In [174]: r = pd.SparseDataFrame((cv.fit_transform(df.select_dtypes('object').add(' ').sum(1)) != 0) * 1,
     ...:                        df.index,
     ...:                        cv.get_feature_names(),
     ...:                        default_fill_value=0)
     ...:
     ...:

In [175]: r
Out[175]:
   jones  llc  co  blue  alpha
0      1    1   0     0      0
1      1    0   1     0      1
2      0    0   0     1      0
© www.soinside.com 2019 - 2024. All rights reserved.