如何在条形图中从一列列表中绘制词频

问题描述 投票:0回答:1

我有数据框

1

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

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

python pandas matplotlib twitter
1个回答
3
投票
  • 主要要求是使用
    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)

© www.soinside.com 2019 - 2024. All rights reserved.