python数据分析之pandas(13)高级数据聚合

之前通过map函数,可以对列进行处理,这节主要学习transform和apply函数

1. transform函数

transform()函数更适用于聚合操作,但是它对参数有特定要求:作为参数的函数必须生成一个标量(聚合),因为只有这样才能进行广播
frame.groupby(‘color’).transform(np.sum).add_prefix(‘tot_’)

>>> import numpy as np
>>> 
>>>> frame = pd.DataFrame({'color': ['white', 'black', 'white', 'white'], 'status
>>> frame
   color status  value1  value2
0  white     up       2       4
1  black     up       3       5
2  white   down       4       8
3  white   down       1       

frame.groupby('color').transform(np.sum).add_prefix('tot_')
   tot_status tot_value1 tot_value2
0  updowndown          7         15
1          up          3          5
2  updowndown          7         15
3  updowndown          7         15
>>>

2. apply函数

frame.groupby([‘color’, ‘status’]).apply(lambda x: x.max())

>>> frame = pd.DataFrame({'color': ['white', 'black', 'white', 'white'], 'status
>>> frame
   color status  value1  value2
0  white     up       2       4
1  black     up       3       5
2  white   down       4       8
3  white   down       1       3
>>> frame.groupby(['color', 'status']).apply(lambda x:x.max())
              color status  value1  value2
color status
black up      black     up       3       5
white down    white   down       4       8
      up      white     up       2       4
>>>

可见,在原来的基础上,增加了black up组合

发布了127 篇原创文章 · 获赞 10 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/u012599545/article/details/104436344