pandas ,groupby和count [英] Pandas, groupby and count

查看:104
本文介绍了 pandas ,groupby和count的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框

>>> df = pd.DataFrame({'user_id':['a','a','s','s','s'],
                    'session':[4,5,4,5,5],
                    'revenue':[-1,0,1,2,1]})

>>> df
   revenue  session user_id
0       -1        4       a
1        0        5       a
2        1        4       s
3        2        5       s
4        1        5       s

会话和收入的每个值代表一种类型,我想计算每种类型的数量,例如user_id=arevenue=-1session=4的数量为1.

And each value of session and revenue represents a kind of type, and I want to count the number of each kind say the number of revenue=-1 and session=4 of user_id=a is 1.

我发现在groupby()无法输出我想要的结果之后,简单调用count()函数.

And I found simple call count() function after groupby() can't output the result I want.

>>> df.groupby('user_id').count()
         revenue  session
user_id
a              2        2
s              3        3

我该怎么办?

推荐答案

您似乎想一次按几列分组:

You seem to want to group by several columns at once:

df.groupby(['revenue','session','user_id'])['user_id'].count()

应该给你想要的东西

这篇关于 pandas ,groupby和count的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆