python - 计算 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 的解决方案将不胜感激。
解决方案
我不确定这是最好的解决方案,但我想出了以下
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}
你认为它符合你的目的吗?
推荐阅读
- css - SASS/SCSS mixin 来生成 css 网格类 - IE 11 需要额外的 20px 间隙列
- c# - 如何从分隔字符串列表中获取不同的列表
- angular - 以角度使用 Typescript 文件中的 css 类或变量
- c++ - 在 C++ 中正确设计具有许多常量的项目
- xml - SOAP 封送处理的 Spring 5 Web 服务客户端问题
- php - 在 php 中执行 bash if else 命令(bash vs php)
- gams-math - 如何显示一些二维参数?
- php - php fwrite到xls文件空白单元格不显示
- django - 配置 caddy、S3 和 CloudFront 的正确方法
- c# - 处理转换