• 破周三,前不着村后不着店的,只好学pandas了,你该这么学,No.9


    如果图片无法观看,请移步 https://blog.csdn.net/hihell

    周三了,一个星期最难的一天

    大中间的,今天还这么热

    5月份,36度的高温

    天空飘过几个字

    屋里学pandas最得劲
    在这里插入图片描述

    Groupy DataFrame with Index Levels and Columns

    说白了就是通过index和columns混合分组

    例子走起,(不赶紧写例子,都不知道要怎么解释啦)

    import pandas as pd
    
    arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
              ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
    
    index = pd.MultiIndex.from_arrays(arrays=arrays,names=['first','second'])
    
    df = pd.DataFrame({'A':[3,1,4,5,9,2,6,1],
                       'B':[1,1,1,1,2,2,3,3]},index=index)
    
    
    print(df)
    
    

    有例子,就有例子展示,对吧

                  A  B
    first second      
    bar   one     3  1
          two     1  1
    baz   one     4  1
          two     5  1
    foo   one     9  2
          two     2  2
    qux   one     6  3
          two     1  3
    

    接下来,大招展示的环节的

    我要按照second的index索引和B列进行分组

    代码先行一步,效果稍后就来

    在这里插入图片描述

    grouped = df.groupby([pd.Grouper(level=1),'B']).sum()
    print(grouped)
    

    注意看到groupby里面有两个值,一个是pd.Grouper(level=1) 这个为second的index
    第二个为B columns

    在这里插入图片描述
    手太抖了,没画好,灵魂画手

    主要就是为了让你看明白,分组是怎么计算的哦~

    当然,你也可以通过index的名字进行分组

    df.groupby([pd.Grouper(level='second'), 'A']).sum()
    

    和上面的效果是一样一样的

    甚至,我们可以直接简写成

    df.groupby(['second', 'A']).sum()
    

    在这里插入图片描述

    分组之后的数据可以选择部分,也可以迭代

    这个部分,其实我们已经实现过了

    再拿出来,重温一下

    df = pd.DataFrame({'A':['bar', 'bar', 'foo', 'foo', 'foo', 'foo', 'foo'],
                       'B':['one', 'two', 'one', 'two', 'one', 'two', 'three'],
                       'C':[3,1,4,5,9,2,6],
                       'D':[1,1,1,1,2,2,3]})
    
    
    print(df)
    
    grouped = df.groupby('A')
    
    for name,group in grouped:
        print(name)
        print(group)
    

    看到分组的名字分别是bar和foo,熟悉吧,常规操作

    迭代的时候,用for in 循环即可

    bar
         A    B  C  D
    0  bar  one  3  1
    1  bar  two  1  1
    foo
         A      B  C  D
    2  foo    one  4  1
    3  foo    two  5  1
    4  foo    one  9  2
    5  foo    two  2  2
    6  foo  three  6  3
    

    如果按照多keys分组,例如groupby(['A','B'])

    它会自然而然的形成一个元组name

    在这里插入图片描述
    可以迭代,就可以部分选择,上篇博客有哦!

    bars = grouped.get_group('bar') # 通过分组的名字
    print(bars)
    

    另一个呢?

    df.groupby(['A', 'B']).get_group(('bar', 'one'))
    

    唉,对喽,这么写,就比较对了

    难度系数的大了,要来了,聚合函数

    首先看一下内置的聚合函数

    sum(), mean(), max(), min(), count(), size(), describe()
    

    竟然才这么几个,那是因为我没写全

    在这里插入图片描述

    这个咱们已经操作很多次了

    接下来可以看一个高级一些的

    可自定义函数,传入agg方法中
    

    我们还是通过刚才的数据进行分析

     	A      B  C  D
    0  bar    one  3  1
    1  bar    two  1  1
    2  foo    one  4  1
    3  foo    two  5  1
    4  foo    one  9  2
    5  foo    two  2  2
    6  foo  three  6  3
    

    按照A和B进行分组
    A有2个值,B有3个值,所以分组之后形成5组

    看清楚,不要眨眼,操作来了

    grouped = df.groupby(['A','B'])
    print(grouped.agg('mean'))
    

    在这里插入图片描述
    思路转换,单列求平均值

    grouped = df.groupby(['A','B'])
    print(grouped['C'].agg('mean'))
    

    继续思路转换,给单列多个聚合函数

    print(grouped['C'].agg(['mean','sum']))
    

    很厉害,学到了吧

    在这里插入图片描述

    继续来,不要怕,求多种聚合运算的同时更改列名

    print(grouped['C'].agg([('A','mean'),('B','max')]))
    

    在这里插入图片描述

    不同的列运用不同的聚合函数

    print(grouped.agg({'C':['sum','mean'],'D':['min','max']}))
    

    在这里插入图片描述

    这些都是agg干的,我还可以继续编哦~

    groupby中,可以修改成无索引形式
    注意核心加了一个参数as_index=False

    
    grouped = df.groupby(['A','B'],as_index=False)
    
    print(grouped.agg({'C':['sum','mean'],'D':['min','max']}))
    

    在这里插入图片描述

    最后一个操作,agg里面是可以使用自定义的聚合函数

    一般,都是这个案例,我呢,当然不能例外啦

    grouped = df.groupby('A')
    
    def max_min(group):
        return group.max()-group.min()
    
    print(grouped.agg(max_min))
    

    agg(自定义的函数)

    这个地方的自定义函数,还支持lambda的哦~

    在这里插入图片描述

    迷糊了吧,迷糊也没事,拿的住手机就行

    拍这里,拍这个里

    在这里插入图片描述

  • 相关阅读:
    【漏洞】【Druid】Druid未授权访问漏洞,修复方案。springboot
    linux shell 获取java版本号
    SpringBoot 通过配置禁用swagger
    string.format()详解
    Linux 下杀毒软件 clamav 0.104.2 离线安装及测试(CentOS7)
    MySQL密码复杂度策略
    Tcpdump抓包命令
    狄尔沃斯定理(Dilworth's theorem)
    docker容器安装TensorFlow_gpu 版本遇到的坑。。。
    C++ 11 make_shared
  • 原文地址:https://www.cnblogs.com/happymeng/p/11044927.html
Copyright © 2020-2023  润新知