Python 基于年份绘制类别计数的链接方法

Python 基于年份绘制类别计数的链接方法,python,pandas,Python,Pandas,我有这样一个数据帧: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df = pd.DataFrame({'Year': [1901,1901,1902,1902], 'Category': list('ABCC'), 'Shared': [1,1,2,2]}) 我喜欢根据年份来计算类别数。 到目前为止,我已经做到了: new_df = df.groupby(

我有这样一个数据帧:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame({'Year': [1901,1901,1902,1902], 'Category': list('ABCC'), 'Shared': [1,1,2,2]})
我喜欢根据年份来计算类别数。 到目前为止,我已经做到了:

new_df = df.groupby(['Year','Category']).count().unstack()
new_df.columns = new_df.columns.droplevel()
new_df.reset_index().drop('Year',axis=1).sum().plot.bar()
这很有效,并给出了以下绘图:

有没有办法使用链式命令获得相同的结果?

例如:

(df.groupby(['Year','Category'])
.count()
.unstack()
.droplevel()
.reset_index()
.drop('Year',axis=1)
.sum().plot.bar())

我得到了非常简单的答案

df['Category'].value_counts().plot.bar()
另外,感谢Scott Boston设计了替代解决方案:

df['Category'].value_counts().sort_index().plot.bar()
df.groupby('Category')['Shared'].count().plot.bar()
df.groupby(['Year','Category'])['Shared'].count().sum(level=1).plot.bar()

您需要使用count(特别是非null)还是使用size
df.groupby('Category').size().plot.bar()
@ayhan没有nans。然后我可能会选择
df.groupby('Category')['Year'].count().plot.bar()
,并添加排序索引以获得完全相同的输出
df['Category'].value_counts().sort_index().plot.bar()
df.groupby('Category')['Shared'].count().plot.bar()
df.groupby(['Year','Category'])['Shared count().sum(level=1)。plot.bar()