AnNg
AnNg

Reputation: 75

How to show wordcloud from a dataframe in Python

Currently, i have a dataframe contain words and weight (tf*idf) and i wanna show words which are arranged following weight in wordcloud.

Dataframe is on the left image.

def generate_wordcloud(words_tem):
    word_cloud = WordCloud(width = 512, height = 512, background_color='white', stopwords= None, max_words=20).generate(words_tem)
    plt.figure(figsize=(10,8),facecolor = 'white', edgecolor='blue')
    plt.imshow(word_cloud, interpolation='bilinear')
    plt.axis('off')
    plt.tight_layout(pad=0)
    plt.show()


tfidf = TfidfVectorizer(data, lowercase = False)
tfs = tfidf.fit_transform([data]) 

feature_names = tfidf.get_feature_names()

df = pd.DataFrame(tfs.T.toarray(), index=feature_names, columns= ['weight'])
df = df.sort_values(by = 'weight', ascending = False)
word_lists = df.index.values
unique_str  = ' '.join(word_lists)
print(df[0:20])
generate_wordcloud(unique_str)

enter image description here

Upvotes: 5

Views: 10291

Answers (1)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15568

The most common package used is called wordcloud. See https://github.com/amueller/word_cloud/blob/master/README.md

python -m pip install wordcloud

Or conda

conda install -c conda-forge wordcloud 

You can do something like: from wordcloud import WordCloud

import matplotlib.pyplot as plt
% matplotlib inline # only if using notebooks

 
 text = your_text_data

# Generate a word cloud image
wordcloud = WordCloud().generate(text)

# Display the generated image:
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

Similar to above, instead of text, your flow # Step starting from TF-IDF model from from gensim.models import TfidfModel but yours too would work as we just make a tuple of (term,weight).

tfidf = TfidfModel(vectors)

# Get TF-IDF weights

weights = tfidf[vectors[0]]


# Get terms from the dictionary and pair with weights

weights = [(dictionary[pair[0]], pair[1]) for pair in weights]


# Generate the cloud

wc = WordCloud()
wc.generate_from_frequencies(weights)
...

Upvotes: 8

Related Questions