簡體   English   中英

計算多個子字符串出現在數據框列中的次數

[英]Count the number of times multiple substrings appear in dataframe column

我有一個數據框,其中一列中有一個句子列表,並且正在嘗試創建一個新列,該列等於字符串列表出現的次數。

例如,相關的數據框看起來像

book['sentences']
0 The brown dog jumped over the big moon
1 The brown fox slid under the brown log

我試圖計算每個句子中出現“棕色”,“超過”和“對數”的次數(即新列等於2和3)。

我知道我可以使用str.count做到這一點,但一次只能輸入一個字符串,然后我必須將它們加起來

book['count_brown'] = book['sentences'].str.count('brown')
book['count_over'] = book['sentences'].str.count('over')
book['count_log'] = book['sentences'].str.count('log')
book['count'] = book['count_brown']+book['count_over']+book['count_log']

我正在搜索的字符串列表超過300個字,因此即使出現循環也不是最佳選擇。 有一個更好的方法嗎?

Ganky!

lst = ['brown', 'over', 'log']

book['sentences'].str.extractall(
    '({})'.format('|'.join(lst))
).groupby(level=0)[0].value_counts().unstack(fill_value=0)

0  brown  log  over
0      1    0     1
1      2    1     0

與piRSquared的解決方案相似,但使用get_dummiessum作為計數。

df
                                sentences
0  The brown dog jumped over the big moon
1  The brown fox slid under the brown log

words = ['brown', 'over', 'log']
df = df.sentences.str.extractall('({})'.format('|'.join(words)))\
                           .iloc[:, 0].str.get_dummies().sum(level=0)
df
   brown  log  over
0      1    0     1
1      2    1     0

如果要對單個列中的所有單詞進行按行計數,只需沿第一個軸求和即可。

df.sum(1)
0    2
1    3
dtype: int64 

借助nltk頻率分布,您可以非常輕松地做到這一點,即

import nltk 
lst = ['brown', 'over', 'log']
ndf = df['sentences'].apply(nltk.tokenize.word_tokenize).apply(nltk.FreqDist).apply(pd.Series)[lst].fillna(0)

輸出:

brown  over  log
0    1.0   1.0  0.0
1    2.0   0.0  1.0

求和

ndf['count'] = ndf.sum(1)
brown  over  log  count
0    1.0   1.0  0.0    2.0
1    2.0   0.0  1.0    3.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM