首页 > 解决方案 > 计算 DataFrame 中标记化项目的单词

问题描述

我有一个 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 的解决方案将不胜感激。

标签: pythonlistnltkfrequencyword-count

解决方案


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

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}

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


推荐阅读