groupby()以及绘图"/>
groupby()以及绘图
1.groupby作用
groupby函数主要是用来进行数据的分组以及分组后的运算
该函数的语法顺序和逻辑执行顺序(我习惯是下面这样的书写顺序):
df.groupby([Column1,Column2])[Condition1].agg({Column3: "mean",Column4:"sum"}).reset_index()
2.举例
写法1:
a = df.groupby(['daily','behavior_type'])['user_id'].agg('count')
pd.DataFrame(a)
写法2:
table_time = df.groupby(['daily','behavior_type'])['user_id'].agg('count').unstack()
table_time
绘图为:
table_time.plot.bar(figsize=(10,5))
还可以用Pyecharts进行绘图:
from pyecharts import options as opts
from pyecharts.charts import Barc = (Bar().add_xaxis(list(table_time.index)).add_yaxis("buy", list(table_time.buy)).add_yaxis("cart", list(table_time.cart)).add_yaxis("collect", list(table_time.collect)).add_yaxis("pv", list(table_time.pv)).set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)),title_opts=opts.TitleOpts(title="24小时的用户行为"),).render("bar_daily.html")
)
写法3:
b = df.groupby(['daily','behavior_type'])['user_id'].agg('count').reset_index().rename(columns={'user_id':'num'})
b
相应绘图为:
sns.barplot(x='daily',y='num',hue='behavior_type',data=b)
3.unstack()和stack()
stack 的作用就是可以将横向的表头(列名)转成纵向的索引列展示,对于多行表头而言,具体要转换哪一行取决于 level 参数,如果不指定,则默认转换最下面一行表头,而unstack 则相反(stack就相当于聚堆,而unstack为解除这个堆)
经过stack可得到下表:
更多推荐
groupby()以及绘图
发布评论