groupby()以及绘图

编程入门 行业动态 更新时间:2024-10-04 11:18:46

<a href=https://www.elefans.com/category/jswz/34/1740990.html style=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()以及绘图

本文发布于:2024-02-28 00:29:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1766919.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:groupby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!