【问题标题】:How to show wordcloud from a dataframe in Python如何在 Python 中从数据框中显示 wordcloud
【发布时间】:2018-12-21 01:28:01
【问题描述】:

目前,我有一个包含单词和权重 (tf*idf) 的数据框,我想在 wordcloud 中显示按照权重排列的单词。

数据框在左图。

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)

【问题讨论】:

    标签: python nlp word-cloud


    【解决方案1】:

    最常用的包是wordcloud。看 https://github.com/amueller/word_cloud/blob/master/README.md

    python -m pip install wordcloud
    

    或者康达

    conda install -c conda-forge 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()
    

    类似于上面,而不是文本,您的流程 # 从 TF-IDF 模型开始从 from gensim.models import TfidfModel 但你的也可以,因为我们只是创建了一个 (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)
    ...
    

    【讨论】:

    • 我想在数据框中生成以下权重。 Small weight small letter and other.Ex: battery: 0.3648 是单词列表中权重最高的,表示将是 wordcloud 中最大的字母。
    • 是的,你可以这样做。更新了我的答案
    • 抱歉,我不理解您代码中的“向量”。包含什么?
    • 是单词的重量。啊,我有一个使用这种方法的例子。 scss.tcd.ie/~munnellg/projects/visualizing-text.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2020-04-14
    • 2017-12-01
    • 2019-07-28
    • 1970-01-01
    相关资源
    最近更新 更多