Skip to main content
 首页 » 编程设计

python之Pandas 聚合图

2024年12月31日8qq78292959

z=t.groupby("CUSAGE").aggregate({'ZDIVND':['nunique','count']}) 

我想根据上述代码绘制“CUSAGE”与 ZDIVND's 计数的条形图。对上述任何帮助将不胜感激。

谢谢

请您参考如下方法:

我想使用另一种聚合解决方案来避免在列中使用 MultiIndex - 在 groupby 之后指定带有聚合函数列表的列:

t = pd.DataFrame({ 
        'CUSAGE':list('aaaccc'), 
         'ZDIVND':[4,5,4,5,5,5] 
}) 
 
print (t) 
  CUSAGE  ZDIVND 
0      a       4 
1      a       5 
2      a       4 
3      c       5 
4      c       5 
5      c       5 
 
z=t.groupby("CUSAGE")['ZDIVND'].agg(['nunique','count']) 
print (z) 
        nunique  count 
CUSAGE                 
a             2      3 
c             1      3 

然后:

#if want plot both columns together 
z.plot.bar() 
 
#if want plot only count column 
z['count'].plot.bar() 

或者使用GroupBy.count :

t.groupby("CUSAGE")['ZDIVND'].count().plot.bar()