pandas 根据第二列的唯一值计算groupby后列的总和

qyzbxkaa  于 2023-03-06  发布在  其他
关注(0)|答案(2)|浏览(140)

我有一个dataframe,其中有类似gp1, gp2, gp3, id, sub_id, activity的列

usr gp2 gp3 id  sub_id  activity
1   IN  ASIA    1   1   1
1   IN  ASIA    1   2   1
1   IN  ASIA    2   9   0
2   IN  ASIA    3   4   1
2   IN  ASIA    3   5   1
2   IN  ASIA    4   6   1
2   IN  ASIA    4   7   0
2   IN  ASIA    4   8   0

我想通过在usr, gp1, gp2上分组来聚合上述 Dataframe ,并计算两列,一列是“帐户(id)”,这是每个组的唯一id的数量,然后是实际(活动),这是基于每个唯一“id”的Activity
for example, if id = 1, the activity sum would be 1 not 2

usr gp1 gp3 id  Activity
1   IN  ASIA    2   1
2   IN  ASIA    2   2

df.groupby(['usr', 'gp2', 'gp3']).agg({'id': pd.Series.nunique, 'activity': LOGIC_REQUIRED})
pieyvz9o

pieyvz9o1#

使用GroupBy.apply对多个(相关)列进行操作:

df.drop(columns='sub_id').groupby(['usr', 'gp2', 'gp3'])\
    .apply(lambda x: pd.DataFrame({'id': [x['id'].nunique()],
                                   'activity': [x[x.activity.ne(0)].drop_duplicates(subset='id')['activity'].sum()]})
           .set_index('id')).reset_index()
usr gp2   gp3  id  activity
0    1  IN  ASIA   2         1
1    2  IN  ASIA   2         2
3qpi33ja

3qpi33ja2#

import pandas as pd

df = pd.DataFrame({'usr':[1, 1, 1, 2, 2, 2, 2, 2],
          'gp2':['IN', 'IN', 'IN', 'IN', 'IN', 'IN', 'IN', 'IN'],
          'gp3':['ASIA', 'ASIA', 'ASIA', 'ASIA', 'ASIA', 'ASIA', 'ASIA', 'ASIA'],
          'id':[1, 1, 2, 3, 3, 4, 4, 4],
          'sub_id':[1, 2, 9, 4, 5, 6, 7, 8],
          'activity':[1, 1, 0, 1, 1, 1, 0, 0],          
          })

df = (df.groupby(['usr', 'gp2', 'gp3'])
        .agg({'id':'nunique'})
        .reset_index(level=['usr', 'gp2', 'gp3'])
        )
df['Activity'] = df.groupby(['usr', 'gp2', 'gp3']).ngroup().add(1)
usr gp2   gp3  id  Activity
0    1  IN  ASIA   2         1
1    2  IN  ASIA   2         2

相关问题