Generate word cloud from single-column Pandas dataframe

北城以北 提交于 2019-12-22 08:42:44

问题


I have a Pandas dataframe with one column: Crime type. The column contains 16 different "categories" of crime, which I would like to visualise as a word cloud, with words sized based on their frequency within the dataframe.

I have attempted to do this with the following code:

To bring the data in:

fields = ['Crime type']

text2 = pd.read_csv('allCrime.csv', usecols=fields)

To generate the word cloud:

wordcloud2 = WordCloud().generate(text2)
# Generate plot
plt.imshow(wordcloud2)
plt.axis("off")
plt.show()

However, I get this error:

TypeError: expected string or bytes-like object

I was able to create an earlier word cloud from the full dataset, using the following code, but I want the word cloud to only generate words from the specific column, 'crime type' ('allCrime.csv' contains approx. 13 columns):

text = open('allCrime.csv').read()
wordcloud = WordCloud().generate(text)
# Generate plot
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

I'm new to Python and Pandas (and coding generally!) so all help is gratefully received.


回答1:


The problem is that the WordCloud.generate method that you are using expects a string on which it will count the word instances but your provide a pd.Series.

Depending on what you want the word cloud to generate on you can either do:

  1. wordcloud2 = WordCloud().generate(' '.join(text2['Crime Type'])), which would concatenate all words in your dataframe column and then count all instances.

  2. Use WordCloud.generate_from_frequencies to manually pass the computed frequencies of words.



来源:https://stackoverflow.com/questions/43606339/generate-word-cloud-from-single-column-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!