python - 如何计算熊猫系列中的特定单词?
问题描述
我正在尝试计算 pandas DataFrame 中的关键字数量,如下所示:
df = pd.read_csv('amazon_baby.csv')
selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']
selected_words 必须从系列中计算:df['review']
我努力了
def word_counter(sent):
a={}
for word in selected_words:
a[word] = sent.count(word)
return a
接着
df['totalwords'] = df.review.str.split()
df['word_count'] = df.totalwords.apply(word_counter)
----------------------------------------------------------------------------
----> 1 df['word_count'] = df.totalwords.apply(word_counter)
c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
3192 else:
3193 values = self.astype(object).values
-> 3194 mapped = lib.map_infer(values, f, convert=convert_dtype)
3195
3196 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()
<ipython-input-51-cd11c5eb1f40> in word_counter(sent)
2 a={}
3 for word in selected_words:
----> 4 a[word] = sent.count(word)
5 return a
AttributeError: 'float' object has no attribute 'count'
有人可以帮忙吗..?我猜这是因为系列中的一些错误值不是字符串。. .
有些人尝试提供帮助,但问题是 DataFrame 中的各个单元格中有句子。
我需要提取所选单词的计数,最好以字典的形式,并将它们存储在具有相应行的同一数据帧中的新列中。
解决方案
假设您的数据框看起来像这样,
df=pd.DataFrame({'A': ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate','great', 'fantastic', 'amazing', 'love', 'horrible']})
print(df)
A
0 awesome
1 great
2 fantastic
3 amazing
4 love
5 horrible
6 bad
7 terrible
8 awful
9 wow
10 hate
11 great
12 fantastic
13 amazing
14 love
15 horrible
selected_words=['awesome','great','fantastic']
df.loc[df['A'].isin(selected_words),'A'].value_counts()
[out]
great 2
fantastic 2
awesome 1
Name: A, dtype: int64
推荐阅读
- python-3.x - 在 Python 中使用 Azure Graph API 使用基于筛选器的查询参数
- java - ExecutorService 不一致
- python - 如何基于组 odoo 13 加载 css
- c - 如何调试/修复像素数组中的索引越界错误?
- javascript - 如何使用 React.js 重构 map 方法中的代码冗余
- apache-spark - 访问结构属性的怪癖 - 可以通过索引而不是名称访问属性
- constraints - Optaplanner 任务分配中没有解决硬约束
- java - 将 DTO 对象作为字节存储在 SQL 表中是否是一种好习惯
- angular - 如何访问 ViewChildren 中元素的 ID?
- java - 位置管理器的 AddGpsStatusListener 在 android 10 中不起作用