【问题标题】:How to plot word frequency, from a column of lists, in a bar chart如何在条形图中从一列列表中绘制词频
【发布时间】:2021-04-03 05:23:15
【问题描述】:

我有数据框

我正在努力在条​​形图中显示所有推文、真实推文和虚假推文的前 10 个单词。有什么建议吗?

将所有文本分成单词,计算频率,选择 10 个最常见的并绘制它们。我认为这样的事情可以工作,但作为一个新手,我不确定如何实施。

提前感谢您的帮助:)

【问题讨论】:

    标签: python pandas matplotlib twitter


    【解决方案1】:
    • 主要要求是使用pandas.Series.explode 分隔list 中的所有值以分隔行。
    • .groupby 并聚合 .count 列中的值,然后 .sort_values
    • 使用pandas.DataFrame.plot.bar 绘制文字
    import pandas as pd
    import matplotlib.pyplot as plt
    
    # test dataframe
    df = pd.DataFrame({'lemmatized': [['se', 'acuerdan', 'de', 'la', 'pelicula el', 'dia'], ['milenagimon', 'miren', 'sandy', 'en', 'ny', 'tremenda'], ['se', 'acuerdan', 'de']]})
    
    # display(df)
                                          lemmatized
    0       [se, acuerdan, de, la, pelicula el, dia]
    1  [milenagimon, miren, sandy, en, ny, tremenda]
    2                             [se, acuerdan, de]
    
    # use explode to expand the lists into separate rows
    dfe = df.lemmatized.explode().to_frame().reset_index(drop=True)
    
    # groupby the values in the column, get the count and sort
    dfg = dfe.groupby('lemmatized').lemmatized.count() \
                                   .reset_index(name='count') \
                                   .sort_values(['count'], ascending=False) \
                                   .head(10).reset_index(drop=True)
    
    # display(dfg)
        lemmatized  count
    0     acuerdan      2
    1           de      2
    2           se      2
    3          dia      1
    4           en      1
    5           la      1
    6  milenagimon      1
    7        miren      1
    8           ny      1
    9  pelicula el      1
    
    # plot the dataframe
    dfg.plot.bar(x='lemmatized')
    

    替代实现

    • 使用.value_counts 而不是.groupby
    # use value_counts and plot the series
    dfe.lemmatized.value_counts().head(10).plot.bar()
    
    • 使用seaborn.countplot
    import seaborn as sns
    
    # plot dfe
    sns.countplot(x='lemmatized', data=dfe, order=dfe.lemmatized.value_counts().iloc[:10].index)
    plt.xticks(rotation=90)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      相关资源
      最近更新 更多