Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用Pandas进行分组、计数并绘制条形图?_Python_Pandas_Dataframe - Fatal编程技术网

Python 如何使用Pandas进行分组、计数并绘制条形图?

Python 如何使用Pandas进行分组、计数并绘制条形图?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个Pandasdataframe,如下所示 year month class ---- ----- ----- 2015 1 1 2015 1 1 2015 1 2 2015 1 2 ... clazz year month clazz 2015 1 1 2 2 1 15 2 2 45 x最终成为的是系列。然后,我

我有一个
Pandas
dataframe,如下所示

year month class ---- ----- ----- 2015 1 1 2015 1 1 2015 1 2 2015 1 2 ... clazz year month clazz 2015 1 1 2 2 1 15 2 2 45
x
最终成为的是
系列
。然后,我执行以下操作以获得一个
DataFrame

df = pd.DataFrame(x)
这让我非常接近。数据最终看起来如下所示

year month class ---- ----- ----- 2015 1 1 2015 1 1 2015 1 2 2015 1 2 ... clazz year month clazz 2015 1 1 2 2 1 15 2 2 45 克拉兹 年-月clazz 2015 1 1 2 2 1 15 2 2 45 但是当我做条形图时,我只看到一个系列。从2015-01年到2019-12年,所需输出仅为一个系列,每月发生多少次
class
1?然后是另一个系列,从2015-01年到2019-12年,每月发生多少次
class
2


关于如何以这种方式操作数据,您有什么想法吗?

A
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')
我们还可以使用:



您可以使用.reset_index()将x数据帧重置为完整的数据帧,然后轻松使用matplotlib。很好的解决方案+1:)
df.pivot_table(index='class',columns=['year','month'],aggfunc='size').plot(kind='bar')