Как получить количество вхождений в список слов (подстрок) в кадре данных pandas? - PullRequest
0 голосов
/ 05 мая 2018

У меня есть фрейм данных Pandas с примерно 1,5 миллионами строк. Я хочу найти количество появлений определенных, выбранных слов (которые все известны) в определенном столбце. Это работает для одного слова.

d = df["Content"].str.contains("word").value_counts()

Но я хочу выяснить вхождения нескольких известных слов, таких как «word1», «word2», из списка. Также word2 может быть word2 или wordtwo, например, так:

word1           40
word2/wordtwo   120

Как мне это сделать?

Ответы [ 2 ]

0 голосов
/ 05 мая 2018

Вы можете создать словарь так:

{w: df["Content"].str.contains(w).sum() for w in words}

Предположим, words - список слов.

0 голосов
/ 05 мая 2018

IMO одним из наиболее эффективных подходов было бы использование sklearn.feature_extraction.text.CountVectorizer , передавая ему словарь (список слов, которые вы хотите сосчитать).

Демо-версия:

In [21]: text = """
    ...: I have a pandas data frame with approximately 1.5 million rows. I want to find the number of occurrences of specific, selected words in a certain colu
    ...: mn. This works for a single word. But I want to find out the occurrences of multiple, known words like "word1", "word2" from a list. Also word2 could
    ...: be word2 or wordtwo, like so"""

In [22]: df = pd.DataFrame(text.split('. '), columns=['Content'])

In [23]: df
Out[23]:
                                             Content
0  \nI have a pandas data frame with approximatel...
1  I want to find the number of occurrences of sp...
2                       This works for a single word
3  But I want to find out the occurrences of mult...
4      Also word2 could be word2 or wordtwo, like so

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

In [25]: vocab = ['word', 'words', 'word1', 'word2', 'wordtwo']

In [26]: vect = CountVectorizer(vocabulary=vocab)

In [27]: res = pd.Series(np.ravel((vect.fit_transform(df['Content']).sum(axis=0))),
                         index=vect.get_feature_names())

In [28]: res
Out[28]:
word       1
words      2
word1      1
word2      3
wordtwo    1
dtype: int64
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...