Python 数据集聚合

Python dataset aggregation

我有一个数据集如下,存储在pd.DataFrame对象中:

df

    topic  student level week
 1   sun      a       1     1
 1   sun      b       2     1
 1   moon     a       3     1
 2   tree     a       1     2
 2   tree     b       2     2
 2   tree     a       3     2
 2   tree     b       4     2
 3   cloud    c       1     2
 3   cloud    b       2     2
 3   cloud    c       3     2
 3   cloud    a       4     2
 3   house    b       5     2

我想汇总每个 id 包含列的学生人数和消息数。

id  topic  num_students num_messages
 1   sun      2            2
 1   moon     1            1
 2   tree     2            4
 3   cloud    3            4
 3   house    1            1

其中 num_students 是每个 id/topic 对 df1 中唯一 student 的数量,num_messages 是 id/topic 对的数量.

有人知道吗?

我认为您需要按 agg with function nunique and size:

进行汇总
d = {'nunique':'num_students','size':'num_messages'}
df1 = (df.groupby(['id','topic'], sort=False)['student']
         .agg(['nunique','size'])
         .rename(columns=d)
         .reset_index())
print (df1)
   id  topic  num_students  num_messages
0   1    sun             2             2
1   1   moon             1             1
2   2   tree             2             4
3   3  cloud             3             4
4   3  house             1             1