Pandas, groupby and count

狂风中的少年 提交于 2019-11-26 11:30:58

问题


I have a dataframe say like this

>>> 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

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.

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

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

How can I do that?


回答1:


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

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

should give you what you want



来源:https://stackoverflow.com/questions/47320572/pandas-groupby-and-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!