计算DataFrame中标记项的单词

时间:2019-01-19 14:49:41

标签: python list nltk frequency word-count

我有一个Pandas DataFrame,其中每一列都包含一个单词标记列表。这是示例数据:

import pandas as pd
df = pd.DataFrame({'example' : pd.Series([
                            ['limited', 'edition', 'vinyl', 'disk'], 
                            ['continental', 'breakfast', 'music', 'table'],
                            ['limited', 'time', 'order']])})

然后我想应用一个简单的计数器来检查单词的频率

选项1:

import nltk
from nltk.probability import FreqDist
word_dist = nltk.FreqDist(str(df.example))
rslt = pd.DataFrame(word_dist.most_common(10), columns=['Word', 'Frequency'])
rslt

    Word Frequency
0        46
1   e    13
2   i    11
3   t    10
...

在此操作无法正常运行后,我按以下方式进行了管理:

选项2:

from collections import defaultdict
for source in sources:
    word_freq = defaultdict(int)
    for text in df.example:
        for word in text:
            word_freq[word] += 1 

pd.DataFrame.from_dict(word_freq, orient='index').sort_values(0, ascending=False).rename(columns={0: 'Frequency'})

            Frequency
limited     2
vinyl       1
continental 1
music       1
...

我想知道是否有更好的方法来计算预先加令牌的内容,或者是否可以修复选项1 ?纯基于Python或scikit-learn的解决方案将不胜感激。

1 个答案:

答案 0 :(得分:0)

我不确定这是最好的解决方案,但是我提出了以下建议

In [3]: freq = {}
In [6]: def count_freq(word):
   ...:     for w in word:
   ...:         if w in list(freq.keys()):
   ...:             freq[w] += 1
   ...:         else:
   ...:             freq[w] = 1
   ...:

In [7]: df.example.apply(count_freq)
Out[7]:
0    None
1    None
2    None
Name: example, dtype: object

In [8]: freq
Out[8]:
{'limited': 2,
 'edition': 1,
 'vinyl': 1,
 'disk': 1,
 'continental': 1,
 'breakfast': 1,
 'music': 1,
 'table': 1,
 'time': 1,
 'order': 1}

您认为它符合您的目的吗?