pandas分组聚合

一 前言

pandas学到分组迭代,那么基础的pandas系列就学的差不多了,自我感觉不错,知识追寻者用pandas处理过一些数据,蛮好用的;

公众号:知识追寻者

知识追寻者(Inheriting the spirit of open source, Spreading technology knowledge;)

二 分组

2.1 数据准备

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

frame = pd.DataFrame({
    'user' : ['zszxz','craler','rose','zszxz','rose'],
    'hobby' : ['reading','running','hiking','reading','hiking'],
    'price' : np.random.randn(5),
    'number' : np.random.randn(5)
})
print(frame)

输出

     user    hobby     price    number
0   zszxz  reading  0.275752 -0.075841
1  craler  running -1.410682  0.259869
2    rose   hiking -0.353269 -0.392659
3   zszxz  reading  1.484604  0.659274
4    rose   hiking -1.348315  2.492047

2.2 分组求均值

提取DataFrame中price 列,根据hobby列进行分组,最后对分好组的数据进行处理求均值;

# 是个生成器
group = frame['price'].groupby(frame['hobby'])
# 求均值
print(group.mean())

输出

hobby
hiking    -0.850792
reading    0.880178
running   -1.410682
Name: price, dtype: float64

Tip: 可以理解为 根据爱好分组,查询价格;查询的列必须是数字,否则求均值时会报异常

如果是根据多列分组则在groupby后面使用列表指定,并且调用求均值函数;输出的值将是分组列,均值结果;

group = frame['price'].groupby([frame['hobby'],frame['user']])
print(group.mean())

输出

hobby    user  
hiking   rose      0.063972
reading  zszxz     0.393164
running  craler   -1.395186
Name: price, dtype: float64

如果对整个DataFrame进行分组,则不再需要提取指定的列;

group = frame.groupby(frame['hobby'])
print(group.mean())

输出

hobby                      
hiking  -0.116659 -0.316222
reading -0.651365  0.856299
running -0.282676 -0.585124

Tip: 求均值后,默认是对数字类型的数据进行分组求均值;非数字列自动忽略

2.3 分组求数量

分组求数量是统计分析中应用最为广泛的函数;如下示例中对DataFrame根据hobby分组,并且调用 size()函数统计个数;此方法常用的统计技巧;

group = frame.groupby(frame['hobby'])
print(group.size())

输出

hobby
hiking     2
reading    2
running    1
dtype: int64

2.4 分组迭代

当对groupby的列只有单个时(示例根据hobby进行分组),可以 使用 key , value 形式 对分组后的数据进行迭代,其中key 是分组的名称,value是分组的数据;

group = frame['price'].groupby(frame['hobby'])
for key , data in group:
    print(key)
    print(data)

输出

hiking
2   -0.669410
4   -0.246816
Name: price, dtype: float64
reading
0    1.362191
3   -0.052538
Name: price, dtype: float64
running
1    0.8963
Name: price, dtype: float64

当对多个列进行分组迭代时,有多少列则需要指定多少个key与其对应,key可以是任何不重复的变量名称

group = frame['price'].groupby([frame['hobby'],frame['user']])
for (key1, key2) , data in group:
    print(key1,key2)
    print(data)

输出

hiking rose
2   -0.019423
4   -2.642912
Name: price, dtype: float64
reading zszxz
0    0.405016
3    0.422182
Name: price, dtype: float64
running craler
1   -0.724752
Name: price, dtype: float64

2.5 分组数据转为字典

可以对分组后的数据转为字典;

dic = dict(list(frame.groupby(frame['hobby'])))
print(dic)

输出

{'hiking':    user   hobby     price    number
2  rose  hiking  0.351633  0.523272
4  rose  hiking  0.800039  0.331646, 
'reading':     user    hobby     price    number
0  zszxz  reading -0.074857 -0.928798
3  zszxz  reading  0.666925  0.606706, 
'running':      user    hobby     price    number
1  craler  running -2.525633  0.895776}

获取key

print(dic['hiking'])

输出

   user   hobby     price    number
2  rose  hiking  0.382225 -0.242055
4  rose  hiking  1.055785 -0.328943

2.6 分组取值

对frame进行hobby分组,就算查询 price 的均值;返回Series;

mean = frame.groupby('hobby')['price'].mean()
print(type(mean))
print(mean)

输出

<class 'pandas.core.series.Series'>
hobby
hiking     0.973211
reading   -1.393790
running   -0.286236
Name: price, dtype: float64

Tip: frame.groupby('hobby')['price'] 与 frame['price'] .groupby(frame['hobby']) 相等

如果想要返回 DataFrame

mean = frame.groupby('hobby')[['price']].mean()
print(type(mean))
print(mean)

输出

<class 'pandas.core.frame.DataFrame'>
            price
hobby            
hiking   0.973211
reading -1.393790
running -0.286236

2.5 Series作为分组

也可以传入Series作为DataFrame的分组列

ser = pd.Series(['hiking','reading','running'])
data = frame.groupby(ser).mean()
print(data)

输出

            price    number
hiking   1.233396  0.313839
reading -0.298887  0.982853
running -0.797734 -1.230811

Tip: 本质上都是数组,除了Series,还可以使用字典,列表,数组,函数作为分组列

2.6 通过索引层级分组

传入级别的名称即可实现层级化索引分组

# 创建2个列,并且指定名称
columns = pd.MultiIndex.from_arrays([['Python', 'Java', 'Python', 'Java', 'Python'],
                                     ['a', 'b', 'a', 'b', 'c']], names=['language', 'alpha'])
frame = pd.DataFrame(np.random.randint(1, 10, (5, 5)), columns=columns)
print(frame)

# 根据language进行分组
print(frame.groupby(level='language', axis=1).sum())
# 根据index进行分组
print(frame.groupby(level='alpha', axis=1).sum())

frame输出如下

language Python Java Python Java Python
alpha         a    b      a    b      c
0             9    9      7    4      5
1             3    4      7    6      6
2             6    6      3    9      1
3             1    1      8    5      2
4             6    5      9    5      4

language分组如下

language  Java  Python
0           13      21
1           10      16
2           15      10
3            6      11
4           10      19

alpha分组如下

alpha   a   b  c
0      16  13  5
1      10  10  6
2       9  15  1
3       9   6  2
4      15  10  4
posted @ 2020-05-07 14:54  知识追寻者  阅读(281)  评论(0编辑  收藏  举报