簡體   English   中英

從 Dataframe Pandas 中的句子中計算最常見的 100 個單詞

[英]Count most frequent 100 words from sentences in Dataframe Pandas

我在 Pandas 數據框中的一列中有文本評論,我想用頻率計數來計算 N 個最頻繁的單詞(在整列中 - 而不是在單個單元格中)。 一種方法是使用計數器通過迭代每一行來計算單詞。 有更好的選擇嗎?

代表性數據。

0    a heartening tale of small victories and endu
1    no sophomore slump for director sam mendes  w
2    if you are an actor who can relate to the sea
3    it's this memory-as-identity obviation that g
4    boyd's screenplay ( co-written with guardian
from collections import Counter
Counter(" ".join(df["text"]).split()).most_common(100)

我很確定會給你你想要的(你可能需要在調用 most_common 之前從計數器結果中刪除一些非單詞)

除了series.value_counts的解決方案,您還可以將series.value_counts用於大量文本/行

 pd.Series(' '.join(df['text']).lower().split()).value_counts()[:100]

您會從基准測試中發現series.value_counts似乎比Counter方法快兩倍 (2X)

對於 3000 行的 Movie Reviews 數據集,總共 400K 個字符和 70k 個單詞。

In [448]: %timeit Counter(" ".join(df.text).lower().split()).most_common(100)
10 loops, best of 3: 44.2 ms per loop

In [449]: %timeit pd.Series(' '.join(df.text).lower().split()).value_counts()[:100]
10 loops, best of 3: 27.1 ms per loop

我將不得不不同意@Zero

對於 91,000 個字符串(電子郵件地址),我發現collections.Counter(..).most_common(n)更快。 但是,如果series.value_counts超過 500k 字 series.value_counts可能仍然更快

%%timeit
[i[0] for i in Counter(data_requester['requester'].values).most_common(5)]
# 13 ms ± 321 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
data_requester['requester'].value_counts().index[:5]
# 22.2 ms ± 597 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

暫無
暫無

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

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