简体   繁体   中英

Count unique elements and sum up values in a pandas groupby operation

I have a table with the follows data:

day         concept    click    item_id 
2015-05-01    A          6     s4P~Hzs1w5R12Dpyn2IK
              B          6     s4P~Hzs1w5R12Dpyn2IK
              C          1     DOwfmfFvdEIZ1IdXqTiu
              D          1     wPaYuIh~t8y7rU3HP43N
              D          7     Ya_M~2N6eX0kem8IgdSp

And I want obtain the count of distint item_id and sum click for all item_id daily , for example:

day         concept       click    count_item_id    
2015-05-01    A          6        1
              B          6        1
              C          1        1
              D          8        2

I work with Python and Pandas library

Use a groupby followed by an agg :

df.groupby(['day', 'concept']).agg({'click' : 'sum', 'item_id' : 'count'})

                    item_id  click
day        concept                
2015-05-01 A              1      6
           B              1      6
           C              1      1
           D              2      8

请检查这是否是您想要的:

df[['day', 'concept']].groupby(['click', 'item_id']).agg(['sum', 'count'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM