import pandas as pd
import numpy as np
data = {
'cls_id': ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B'],
'group_id': [1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2],
'name': ['zs', 'ls', 'ww', 'zl', 'xx', 'uu', 'yy', 'kk', 'ii', 'oo', 'zz', 'qq'],
'height': [178.0, 182.0, 175.5, 168.0, 152.0, 169.0, 173.5, 180.5, 156.5, 172.0, 190.0, 192.0],
'score': [98, 96, 85, 87, 88, 65, 60, 92, 59, 87, 62, 88]
}
index = ['index' + str(temp) for temp in np.arange(12)]
message = pd.DataFrame(data=data, index=index)
print(message)
# 单列
print(message.groupby(by='cls_id')['height'].max())
print(message.groupby(by='cls_id')[['height', 'score']].mean())
# 多列
print(message.groupby(by=['cls_id', 'group_id'])['height'].max())
print(message.groupby(by=['cls_id', 'group_id'])[['height', 'score']].max())
# 可以使用agg求出height 、score 的最大值、均值多个指标
print(message[['height', 'score']].agg([np.max, np.mean]))
# 同时统计身高的最大值、成绩的平均值
print(message.agg({'height': [np.max], 'score': [np.mean]}))
# 求出身高的最大值,求出成绩的最小值、均值
print(message.agg({'height': [np.max], 'score': [np.min, np.mean]}))
# 自定义函数 ---对height列 和score列分别 + 100操作
print(message[['height', 'score']].agg(lambda x: 100+x))
# transform也能实现agg自定义功能
print(message[['height', 'score']].transform(lambda x: 100+x))
print(message.groupby(by='cls_id')[['height', 'score']].transform(np.sum))
简单了解pandas分组聚合
最新推荐文章于 2023-08-02 11:23:57 发布