Nik*_*ngh 2 python attributeerror python-3.x pandas
我试图计算pandas DataFrame中的关键字数量:
df = pd.read_csv('amazon_baby.csv')
selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']
Run Code Online (Sandbox Code Playgroud)
selected_words必须从系列计算:df ['review']
我试过了
def word_counter(sent):
a={}
for word in selected_words:
a[word] = sent.count(word)
return a
Run Code Online (Sandbox Code Playgroud)
然后
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'
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙..?我猜这是因为系列中的某些错误值不是字符串...
有些人尝试过帮助,但问题是DataFrame 中的单个单元格中有句子.
我需要提取所选单词的计数,最好是以字典形式,并将它们存储在具有相应行的同一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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
572 次 |
| 最近记录: |