wordcloud for python中的csv文件

时间:2017-02-12 20:43:21

标签: python csv pandas classification word-cloud

我有一个包含2列的csv文件(数据帧) 第1列包含一个我爱香蕉的句子

和第2列包含我有5 classes

的classe

我需要为每个班级提供一个wordcloud 事实上,每一个对应于每个classes的所有句子都可以做到吗? 它尝试此代码,但ID不起作用

import matplotlib.pyplot as plt
cloud = WordCloud(background_color="white", max_words=20, stopwords=stopwords)
tuples = tuple([tuple(x) for x in df.Phrase.value_counts().reset_index().values])
a = cloud.generate_from_frequencies(tuples)

plt.imshow(a)
plt.axis("off")
plt.title("a")
plt.show()

数据集示例

text                           classe
i love banana                 positive 
i hate banana                 negetive
maybe i love maybe no         neutral
bit yes bit no                not_sure
wooooooooooow                 like_it

1 个答案:

答案 0 :(得分:2)

以下是一个类的示例:positive

假设我们有以下DF:

In [79]: df
Out[79]:
                    text    classe
0          i love banana  positive
1             love apple  positive
2       love, love, love  positive
3          i hate banana  negative
4               it sucks  negative
5  maybe i love maybe no   neutral
6         bit yes bit no  not_sure
7          wooooooooooow   like_it

解决方案:

In [80]: %paste
from wordcloud import WordCloud
from nltk.corpus import stopwords

cloud = WordCloud(background_color="white", max_words=20, stopwords=stopwords.words('english'))

positive_cloud = cloud.generate(df.loc[df.classe == 'positive', 'text'].str.cat(sep='\n'))
plt.figure()
plt.imshow(positive_cloud)
plt.axis("off")
plt.show()
## -- End pasted text --

结果:

enter image description here

一些解释:

生成单个class的文字:

In [81]: df.loc[df.classe == 'positive', 'text'].str.cat(sep='\n')
Out[81]: 'i love banana\nlove apple\nlove, love, love'