问题
I am trying to count the number of keywords from a pandas DataFrame as such:
df = pd.read_csv('amazon_baby.csv')
selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']
The selected_words have to be counted from the Series: df['review']
i have tried
def word_counter(sent):
a={}
for word in selected_words:
a[word] = sent.count(word)
return a
and then
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'
can someone help..? i am guessing it is because of some fault value in the series that is not a string. . .
some people have tried helping but the issue is that the individual cells in the DataFrame have sentences in them.
I need to extract a count of selected words, preferably in dictionary form and store them in a new column in the same dataFrame with the corresponding rows.
Data in csv format
回答1:
Suppose your dataframe looks like this,
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
回答2:
Repeated list.count
in a loop would work, albeit inefficiently, with a list
of values. Complexity would be O(m x n), where m is the number of selected values and n is the total number of values.
With Pandas you can use optimized methods which ensure O(n) complexity. In this case, you can use value_counts followed by reindex:
res = df['A'].value_counts().reindex(selected_words)
print(res)
awesome 1
great 2
fantastic 2
Name: A, dtype: int64
Or, as per @pyd's solution, filter first and then use value_counts
. Both solutions will have O(n) complexity.
回答3:
In your question you seems to be implementing a dict for the count. @pyd have posted a good solution for the counting. The result produced is not a dict. If you are looking for a dictionary as output take a look at this code posted below, which is basically an extension of the solution provided by pyd.
df=pd.DataFrame({'A': ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate','great', 'fantastic', 'amazing', 'love', 'horrible']})
def get_count_dict(data, selected_words):
count_dict = {}
counts = data.loc[data['A'].isin(selected_words), 'A'].value_counts()
for i in range(len(counts.index.tolist())):
count_dict[counts.index.tolist()[i]] = counts[i]
return count_dict
selected_words=['awesome','great','fantastic']
get_count_dict(df, selected_words)
Output : {'fantastic': 2, 'great': 2, 'awesome': 1}
来源:https://stackoverflow.com/questions/52221931/how-to-count-specific-words-from-a-pandas-series