【问题标题】:How to do I groupby, count and then plot a bar chart in Pandas?如何在 Pandas 中分组、计数然后绘制条形图?
【发布时间】:2019-12-06 07:26:42
【问题描述】:

我有一个Pandas 数据框,如下所示。

年月班 ---- ----- ----- 2015 1 1 2015 1 1 2015 1 2 2015 1 2 ...

我希望能够在一个绘图上创建 2 个此数据的条形图系列。如果我可以做一个groupbycount 并最终得到一个data frame,那么我想我可以做一个简单的dataframe.plot.barh

我尝试的是以下代码。

x = df.groupby(['year', 'month', 'class'])['class'].count()

x 最终变成了Series。那么我执行以下操作以获得DataFrame

df = pd.DataFrame(x)

这让我非常接近。数据最终如下所示。

克拉兹 年月克拉兹 2015 1 1 2 2 1 15 2 2 45

但是当我做条形图df.plot.bar() 时,我只看到一个系列。所需的输出只是一个系列,从 2015-01 到 2019-12,class1 每月出现多少次?然后是另一个系列,从 2015-01 到 2019-12,class2 每月出现多少次?

关于如何以这种方式操作数据的任何想法?

【问题讨论】:

  • 您可以使用 .reset_index() 到您的 x DataFrame 以获得完整的 DataFrame,然后轻松使用 matplotlib。

标签: python pandas dataframe


【解决方案1】:

groupby-unstack 应该可以解决问题:

数据

df = pd.DataFrame([[2015, 1, 1],
                    [2015, 1, 1],
                    [2015, 1, 2],
                    [2015, 1, 2],
                    [2015, 1, 2],
                    [2015, 2, 1],
                    [2015, 2, 1],
                    [2015, 2, 1],
                    [2015, 2, 2],
                    [2015, 2, 2]], columns = ['year', 'month', 'class'])

解决方案

df_gb = df.groupby(['year', 'month', 'class']).size().unstack(level=2)

输出

df_gb.plot(kind = 'bar')

【讨论】:

  • 不错的解决方案 + 1:)
【解决方案2】:

我们也可以使用DataFrame.pivot_table:

df.pivot_table(index=['year','month'],columns='class',aggfunc='size').plot(kind='bar')


df.pivot_table(index='class',columns=['year','month'],aggfunc='size').plot(kind='bar')

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2020-05-29
    • 1970-01-01
    • 2021-10-24
    • 2014-08-03
    • 2018-01-06
    • 2021-11-25
    • 2018-04-12
    相关资源
    最近更新 更多