Skip to main content
 首页 » 编程设计

python之Pandas :根据群体进行不同的聚合

2024年10月24日16yyy_WW

假设我有一些数据如下:

patient_id  lab_type  value 
1           food       10 
1           food       8 
2           food       3 
2           food       5 
1           shot       4 
1           shot       10 
2           shot       2 
2           shot       4 

然后我将分组诸如 groupby(['patient_id', 'lab_type'])

之后,我想汇总值,但每个lab_type 都不同。在 food 上,我想使用 mean 进行聚合,在 shot 上,我想使用 sum 进行聚合。

最终数据应该是这样的:

  patient_id  lab_type  value 
  1           food       9 (10 + 8 / 2) 
  2           food       4 (3 + 5 / 2) 
  1           shot       14 (10 + 4) 
  2           shot       6 (2 + 4) 

请您参考如下方法:

On food I'd like to aggregate using mean and on shot I'd like to aggregate using sum.

只需使用 .apply 并传递一个自定义函数:

def calc(g): 
    if g.iloc[0].lab_type == 'shot': 
        return sum(g.value) 
    else: 
        return np.mean(g.value) 
result = df.groupby(['patient_id', 'lab_type']).apply(calc) 

此处 calc 接收每组数据帧,如 Panda's split-apply-combine 所示。 .结果你得到了你想要的:

patient_id  lab_type 
1           food         9 
            shot        14 
2           food         4 
            shot         6 
dtype: float64