首页 > 解决方案 > 如何计算熊猫系列中的特定单词?

问题描述

我正在尝试计算 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 中的各个单元格中有句子。

我需要提取所选单词的计数,最好以字典的形式,并将它们存储在具有相应行的同一数据帧中的新列中。

前几行 csv 的图像 csv 格式的数据

标签: pythonpython-3.xpandasattributeerror

解决方案


假设您的数据框看起来像这样,

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

推荐阅读