Pandas统计分析基础(6):基于groupby的数据分组和分组后的数据可视化&数据聚合方法(agg/apply/transform方法)

✅作者简介:大家好我是Xlong,一枚正在学习COMSOL、Python的工科研究僧
📃个人主页:  Xlong的个人博客主页
🔥系列专栏:   Python大数据分析
💖如果觉得博主的文章还不错的话,请👍支持一下博主哦🤞

目录

一、 基于groupby的数据分组 

1.1 groupby是什么 

1.2 groupby的功能

二、 数据聚合方法 

2.1 使用agg方法聚合数据

2.2 使用apply方法聚合数据 

2.3 使用transform方法聚合数据 

三、 groupby分组后的数据可视化


一、 基于groupby的数据分组 

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False  #针对坐标轴中负号显示不出来的问题
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
print(df7)

运行结果:

                2018年_pop  2018年_gdp  区域
省份                                
北京市            2154   30319.98  华北
天津市            1560   18809.64  华北
河北省            7556   36010.27  华北
山西省            3718   16818.11  华北
内蒙古自治区         2534   17289.22  华北
辽宁省            4359   25315.35  东北
吉林省            2704   15074.62  东北
黑龙江省           3773   16361.62  东北
上海市            2424   32679.87  华东
江苏省            8051   92595.40  华东
浙江省            5737   56197.15  华东
安徽省            6324   30006.82  华东
福建省            3941   35804.04  华东
江西省            4648   21984.78  华东
山东省           10047   76469.67  华东
河南省            9605   48055.86  中南
湖北省            5917   39366.55  中南
湖南省            6899   36425.78  中南
广东省           11346   97277.77  中南
广西壮族自治区        4926   20352.51  中南
海南省             934    4832.05  中南
重庆市            3102   20363.19  西南
四川省            8341   40678.13  西南
贵州省            3600   14806.45  西南
云南省            4830   17881.12  西南
西藏自治区           344    1477.63  西南
陕西省            3864   24438.32  西北
甘肃省            2637    8246.07  西北
青海省             603    2865.23  西北
宁夏回族自治区         688    3705.18  西北
新疆维吾尔自治区       2487   12199.08  西北

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False  #针对坐标轴中负号显示不出来的问题
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(group_region)

 运行结果:

<pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000026980CD1C10>

1.1 groupby是什么 

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False  #针对坐标轴中负号显示不出来的问题
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(len(group_region))

运行结果:

6

import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
for i in group_region:
    print(i)

 运行结果:

('东北',       2018年_pop  2018年_gdp  区域
省份                            
辽宁省        4359   25315.35  东北
吉林省        2704   15074.62  东北
黑龙江省       3773   16361.62  东北)
('中南',          2018年_pop  2018年_gdp  区域
省份                               
河南省           9605   48055.86  中南
湖北省           5917   39366.55  中南
湖南省           6899   36425.78  中南
广东省          11346   97277.77  中南
广西壮族自治区       4926   20352.51  中南
海南省            934    4832.05  中南)
('华东',      2018年_pop  2018年_gdp  区域
省份                           
上海市       2424   32679.87  华东
江苏省       8051   92595.40  华东
浙江省       5737   56197.15  华东
安徽省       6324   30006.82  华东
福建省       3941   35804.04  华东
江西省       4648   21984.78  华东
山东省      10047   76469.67  华东)
('华北',         2018年_pop  2018年_gdp  区域
省份                              
北京市          2154   30319.98  华北
天津市          1560   18809.64  华北
河北省          7556   36010.27  华北
山西省          3718   16818.11  华北
内蒙古自治区       2534   17289.22  华北)
('西北',           2018年_pop  2018年_gdp  区域
省份                                
陕西省            3864   24438.32  西北
甘肃省            2637    8246.07  西北
青海省             603    2865.23  西北
宁夏回族自治区         688    3705.18  西北
新疆维吾尔自治区       2487   12199.08  西北)
('西南',        2018年_pop  2018年_gdp  区域
省份                             
重庆市         3102   20363.19  西南
四川省         8341   40678.13  西南
贵州省         3600   14806.45  西南
云南省         4830   17881.12  西南
西藏自治区        344    1477.63  西南)

import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
for i in group_region:
    print(type(i))
    print(len(i))

 运行结果:

<class 'tuple'>
2
<class 'tuple'>
2
<class 'tuple'>
2
<class 'tuple'>
2
<class 'tuple'>
2
<class 'tuple'>
2

import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
for i in group_region:
    print(i[0])
print('\n')
for i in group_region:
    print(i[1])

 运行结果:

东北
中南
华东
华北
西北
西南


      2018年_pop  2018年_gdp  区域
省份                            
辽宁省        4359   25315.35  东北
吉林省        2704   15074.62  东北
黑龙江省       3773   16361.62  东北
         2018年_pop  2018年_gdp  区域
省份                               
河南省           9605   48055.86  中南
湖北省           5917   39366.55  中南
湖南省           6899   36425.78  中南
广东省          11346   97277.77  中南
广西壮族自治区       4926   20352.51  中南
海南省            934    4832.05  中南
     2018年_pop  2018年_gdp  区域
省份                           
上海市       2424   32679.87  华东
江苏省       8051   92595.40  华东
浙江省       5737   56197.15  华东
安徽省       6324   30006.82  华东
福建省       3941   35804.04  华东
江西省       4648   21984.78  华东
山东省      10047   76469.67  华东
        2018年_pop  2018年_gdp  区域
省份                              
北京市          2154   30319.98  华北
天津市          1560   18809.64  华北
河北省          7556   36010.27  华北
山西省          3718   16818.11  华北
内蒙古自治区       2534   17289.22  华北
          2018年_pop  2018年_gdp  区域
省份                                
陕西省            3864   24438.32  西北
甘肃省            2637    8246.07  西北
青海省             603    2865.23  西北
宁夏回族自治区         688    3705.18  西北
新疆维吾尔自治区       2487   12199.08  西北
       2018年_pop  2018年_gdp  区域
省份                             
重庆市         3102   20363.19  西南
四川省         8341   40678.13  西南
贵州省         3600   14806.45  西南
云南省         4830   17881.12  西南
西藏自治区        344    1477.63  西南

        groupby功能生成的是多个tuple对象,每个tuple对象有两个元素,第一个元素是分类的名字,第二个元素是该分类的所有行构成的DataFrame 

1.2 groupby的功能

import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(group_region.mean())

运行结果:

        2018年_pop     2018年_gdp
区域                           
东北  3612.000000  18917.196667
中南  6604.500000  41051.753333
华东  5881.714286  49391.104286
华北  3504.400000  23849.444000
西北  2055.800000  10290.776000
西南  4043.400000  19041.304000

import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(group_region.describe())

 运行结果:

2018年_pop                            ...  2018年_gdp                      
       count         mean          std  ...        50%         75%       max
区域                                      ...                                 
东北       3.0  3612.000000   839.164465  ...  16361.620  20838.4850  25315.35
中南       6.0  6604.500000  3661.041969  ...  37896.165  45883.5325  97277.77
华东       7.0  5881.714286  2566.326019  ...  35804.040  66333.4100  92595.40
华北       5.0  3504.400000  2398.282469  ...  18809.640  30319.9800  36010.27
西北       5.0  2055.800000  1394.168103  ...   8246.070  12199.0800  24438.32
西南       5.0  4043.400000  2909.317068  ...  17881.120  20363.1900  40678.13

[6 rows x 16 columns]

2. 数据聚合方法 

2.1 使用agg方法聚合数据

import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(df7)

运行结果:

2018年_pop  2018年_gdp  区域
省份                                
北京市            2154   30319.98  华北
天津市            1560   18809.64  华北
河北省            7556   36010.27  华北
山西省            3718   16818.11  华北
内蒙古自治区         2534   17289.22  华北
辽宁省            4359   25315.35  东北
吉林省            2704   15074.62  东北
黑龙江省           3773   16361.62  东北
上海市            2424   32679.87  华东
江苏省            8051   92595.40  华东
浙江省            5737   56197.15  华东
安徽省            6324   30006.82  华东
福建省            3941   35804.04  华东
江西省            4648   21984.78  华东
山东省           10047   76469.67  华东
河南省            9605   48055.86  中南
湖北省            5917   39366.55  中南
湖南省            6899   36425.78  中南
广东省           11346   97277.77  中南
广西壮族自治区        4926   20352.51  中南
海南省             934    4832.05  中南
重庆市            3102   20363.19  西南
四川省            8341   40678.13  西南
贵州省            3600   14806.45  西南
云南省            4830   17881.12  西南
西藏自治区           344    1477.63  西南
陕西省            3864   24438.32  西北
甘肃省            2637    8246.07  西北
青海省             603    2865.23  西北
宁夏回族自治区         688    3705.18  西北
新疆维吾尔自治区       2487   12199.08  西北

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(df7[['2018年_pop','2018年_gdp']].agg(np.sum))  #agg可以对一列或多列执行一个函数

 运行结果:

2018年_pop    139653.00
2018年_gdp    914707.46
dtype: float64

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(df7[['2018年_pop','2018年_gdp']].agg([np.sum,np.max]))#agg可以对一列或多列执行多个函数) 

 运行结果:

            2018年_pop  2018年_gdp
sum      139653  914707.46
amax      11346   97277.77

使用groupby功能分类后,也可以使用此类聚合方法

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(group_region[['2018年_pop','2018年_gdp']].agg([np.mean,np.max]))  #可以让一列或多列执行一个或多个函数

 运行结果:

           2018年_pop            2018年_gdp          
           mean         amax       mean              amax
区域                                            
东北  3612.000000   4359  18917.196667  25315.35
中南  6604.500000  11346  41051.753333  97277.77
华东  5881.714286  10047  49391.104286  92595.40
华北  3504.400000   7556  23849.444000  36010.27
西北  2055.800000   3864  10290.776000  24438.32
西南  4043.400000   8341  19041.304000  40678.13

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(group_region.agg({'2018年_pop':[np.sum,np.max],'2018年_gdp':np.mean}))
#可以通过字典的形式给每一列指定一个函数,字典格式为{行名:该行执行的函数}
#执行的也可以是函数组

 运行结果:

         2018年_pop            2018年_gdp
         sum      amax          mean
区域                               
东北     10836   4359  18917.196667
中南     39627  11346  41051.753333
华东     41172  10047  49391.104286
华北     17522   7556  23849.444000
西北     10279   3864  10290.776000
西南     20217   8341  19041.304000

2.2 使用apply方法聚合数据 

apply不具有执行多种函数的功能

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(group_region['2018年_pop'].apply(np.sum))

运行结果:

区域
东北    10836
中南    39627
华东    41172
华北    17522
西北    10279
西南    20217
Name: 2018年_pop, dtype: int64

2.3 使用transform方法聚合数据 

transform和agg,apply等方法不同,看以下例子:

求得各个地区的人口和gdp总值

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
print(group_region[['2018年_pop','2018年_gdp']].apply(np.sum))

运行结果:

        2018年_pop  2018年_gdp
区域                      
东北    10836.0   56751.59
中南    39627.0  246310.52
华东    41172.0  345737.73
华北    17522.0  119247.22
西北    10279.0   51453.88
西南    20217.0   95206.52

思考:如果我们想要求每个省占其所在地区的人口和GDP的占比,怎么办?

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
groupsum=group_region.transform(np.sum)
print(groupsum)

 运行结果:

2018年_pop  2018年_gdp
省份                            
北京市           17522  119247.22
天津市           17522  119247.22
河北省           17522  119247.22
山西省           17522  119247.22
内蒙古自治区        17522  119247.22
辽宁省           10836   56751.59
吉林省           10836   56751.59
黑龙江省          10836   56751.59
上海市           41172  345737.73
江苏省           41172  345737.73
浙江省           41172  345737.73
安徽省           41172  345737.73
福建省           41172  345737.73
江西省           41172  345737.73
山东省           41172  345737.73
河南省           39627  246310.52
湖北省           39627  246310.52
湖南省           39627  246310.52
广东省           39627  246310.52
广西壮族自治区       39627  246310.52
海南省           39627  246310.52
重庆市           20217   95206.52
四川省           20217   95206.52
贵州省           20217   95206.52
云南省           20217   95206.52
西藏自治区         20217   95206.52
陕西省           10279   51453.88
甘肃省           10279   51453.88
青海省           10279   51453.88
宁夏回族自治区       10279   51453.88
新疆维吾尔自治区      10279   51453.88

        transform方法可以对groupby之后的每个group作用函数,但返回的结果是和原dataframe等长的 

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
groupsum=group_region.transform(np.sum)
print(groupsum['2018年_pop'])

运行结果:

省份
北京市         17522
天津市         17522
河北省         17522
山西省         17522
内蒙古自治区      17522
辽宁省         10836
吉林省         10836
黑龙江省        10836
上海市         41172
江苏省         41172
浙江省         41172
安徽省         41172
福建省         41172
江西省         41172
山东省         41172
河南省         39627
湖北省         39627
湖南省         39627
广东省         39627
广西壮族自治区     39627
海南省         39627
重庆市         20217
四川省         20217
贵州省         20217
云南省         20217
西藏自治区       20217
陕西省         10279
甘肃省         10279
青海省         10279
宁夏回族自治区     10279
新疆维吾尔自治区    10279
Name: 2018年_pop, dtype: int64

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
groupsum=group_region.transform(np.sum)
df7['gdp占区域比例']=df7['2018年_gdp']/ groupsum['2018年_gdp']
print(df7)

 运行结果:

 2018年_pop  2018年_gdp  区域  gdp占区域比例
省份                                          
北京市            2154   30319.98  华北  0.254262
天津市            1560   18809.64  华北  0.157737
河北省            7556   36010.27  华北  0.301980
山西省            3718   16818.11  华北  0.141036
内蒙古自治区         2534   17289.22  华北  0.144986
辽宁省            4359   25315.35  东北  0.446073
吉林省            2704   15074.62  东北  0.265625
黑龙江省           3773   16361.62  东北  0.288302
上海市            2424   32679.87  华东  0.094522
江苏省            8051   92595.40  华东  0.267820
浙江省            5737   56197.15  华东  0.162543
安徽省            6324   30006.82  华东  0.086791
福建省            3941   35804.04  华东  0.103558
江西省            4648   21984.78  华东  0.063588
山东省           10047   76469.67  华东  0.221178
河南省            9605   48055.86  中南  0.195103
湖北省            5917   39366.55  中南  0.159825
湖南省            6899   36425.78  中南  0.147886
广东省           11346   97277.77  中南  0.394940
广西壮族自治区        4926   20352.51  中南  0.082629
海南省             934    4832.05  中南  0.019618
重庆市            3102   20363.19  西南  0.213884
四川省            8341   40678.13  西南  0.427262
贵州省            3600   14806.45  西南  0.155519
云南省            4830   17881.12  西南  0.187814
西藏自治区           344    1477.63  西南  0.015520
陕西省            3864   24438.32  西北  0.474956
甘肃省            2637    8246.07  西北  0.160261
青海省             603    2865.23  西北  0.055685
宁夏回族自治区         688    3705.18  西北  0.072010
新疆维吾尔自治区       2487   12199.08  西北  0.237088

import numpy as np
import pandas as pd
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
groupsum=group_region.transform(np.sum)
df7['gdp占区域比例']=df7['2018年_gdp']/ groupsum['2018年_gdp']
df7['人口占区域比例']=df7['2018年_pop']/ groupsum['2018年_pop']
print(df7)

 运行结果:

2018年_pop  2018年_gdp  区域  gdp占区域比例   人口占区域比例
省份                                                    
北京市            2154   30319.98  华北  0.254262  0.122931
天津市            1560   18809.64  华北  0.157737  0.089031
河北省            7556   36010.27  华北  0.301980  0.431229
山西省            3718   16818.11  华北  0.141036  0.212190
内蒙古自治区         2534   17289.22  华北  0.144986  0.144618
辽宁省            4359   25315.35  东北  0.446073  0.402270
吉林省            2704   15074.62  东北  0.265625  0.249539
黑龙江省           3773   16361.62  东北  0.288302  0.348191
上海市            2424   32679.87  华东  0.094522  0.058875
江苏省            8051   92595.40  华东  0.267820  0.195546
浙江省            5737   56197.15  华东  0.162543  0.139342
安徽省            6324   30006.82  华东  0.086791  0.153600
福建省            3941   35804.04  华东  0.103558  0.095720
江西省            4648   21984.78  华东  0.063588  0.112892
山东省           10047   76469.67  华东  0.221178  0.244025
河南省            9605   48055.86  中南  0.195103  0.242385
湖北省            5917   39366.55  中南  0.159825  0.149317
湖南省            6899   36425.78  中南  0.147886  0.174098
广东省           11346   97277.77  中南  0.394940  0.286320
广西壮族自治区        4926   20352.51  中南  0.082629  0.124309
海南省             934    4832.05  中南  0.019618  0.023570
重庆市            3102   20363.19  西南  0.213884  0.153435
四川省            8341   40678.13  西南  0.427262  0.412574
贵州省            3600   14806.45  西南  0.155519  0.178068
云南省            4830   17881.12  西南  0.187814  0.238908
西藏自治区           344    1477.63  西南  0.015520  0.017015
陕西省            3864   24438.32  西北  0.474956  0.375912
甘肃省            2637    8246.07  西北  0.160261  0.256542
青海省             603    2865.23  西北  0.055685  0.058663
宁夏回族自治区         688    3705.18  西北  0.072010  0.066933
新疆维吾尔自治区       2487   12199.08  西北  0.237088  0.241950

3. groupby分组后的数据可视化

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
groupsum=group_region.transform(np.sum)
df7['gdp占区域比例']=df7['2018年_gdp']/ groupsum['2018年_gdp']
df7['人口占区域比例']=df7['2018年_pop']/ groupsum['2018年_pop']
fig1,ax1=plt.subplots(figsize=(8,8))
drawdf=group_region[['2018年_pop','2018年_gdp']].apply(np.sum)
print(drawdf)

运行结果:

         2018年_pop  2018年_gdp
区域                      
东北    10836.0   56751.59
中南    39627.0  246310.52
华东    41172.0  345737.73
华北    17522.0  119247.22
西北    10279.0   51453.88
西南    20217.0   95206.52

 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False  ##针对坐标轴中负号显示不出来的问题
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
groupsum=group_region.transform(np.sum)
df7['gdp占区域比例']=df7['2018年_gdp']/ groupsum['2018年_gdp']
df7['人口占区域比例']=df7['2018年_pop']/ groupsum['2018年_pop']
fig1,ax1=plt.subplots(figsize=(8,8))
drawdf=group_region[['2018年_pop','2018年_gdp']].apply(np.sum)
drawdf.plot(ax=ax1)
fig1
plt.show()

 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False  ##针对坐标轴中负号显示不出来的问题
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
groupsum=group_region.transform(np.sum)
df7['gdp占区域比例']=df7['2018年_gdp']/ groupsum['2018年_gdp']
df7['人口占区域比例']=df7['2018年_pop']/ groupsum['2018年_pop']
fig1,ax1=plt.subplots(figsize=(8,8))
drawdf=group_region[['2018年_pop','2018年_gdp']].apply(np.sum)
drawdf.plot(ax=ax1)
fig2,ax2=plt.subplots(1,2,figsize=(12,6))
group_region[['2018年_pop','2018年_gdp']].agg(np.sum).plot.bar(ax=ax2,subplots=True)
ax2[0].set_ylabel('人口(万人)')
ax2[1].set_ylabel('GDP(亿元)')
fig2
plt.show()
fig2.savefig('pop and gdp.jpg',bbox_inches = 'tight')

 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False  ##针对坐标轴中负号显示不出来的问题
pop=pd.read_excel('GDPandPopulation.xlsx',sheet_name='Population',index_col=0)
gdp=pd.read_excel('GDPandPopulation.xlsx',sheet_name='GDP',index_col=0)
df5=pd.concat([pop,gdp],axis=0,keys=['pop','gdp'])  #不用改名字即可合并
df6=pop.join(gdp,lsuffix='_pop', rsuffix='_gdp') #两个dataframe列名相同,需要加lsuffix或rsuffix在左边/右边的列名上加后缀来区分
region=pd.read_excel('GDPandPopulation.xlsx',sheet_name='region',index_col=0)
df7=df6.join(region) #没有重名列可以直接使用
group_region=df7.groupby(by='区域')  #以'区域'这一列进行分类,值相同的行被并为一类
groupsum=group_region.transform(np.sum)
df7['gdp占区域比例']=df7['2018年_gdp']/ groupsum['2018年_gdp']
df7['人口占区域比例']=df7['2018年_pop']/ groupsum['2018年_pop']
fig1,ax1=plt.subplots(figsize=(8,8))
drawdf=group_region[['2018年_pop','2018年_gdp']].apply(np.sum)
drawdf.plot(ax=ax1)
fig2,ax2=plt.subplots(1,2,figsize=(12,6))
group_region[['2018年_pop','2018年_gdp']].agg(np.sum).plot.bar(ax=ax2,subplots=True)
ax2[0].set_ylabel('人口(万人)')
ax2[1].set_ylabel('GDP(亿元)')
fig2
#plt.show()
fig2.savefig('pop and gdp.jpg',bbox_inches = 'tight')
df_sum=group_region[['2018年_pop','2018年_gdp']].agg(np.sum)
df_sum['人均GDP']=df_sum['2018年_gdp']/df_sum['2018年_pop']
print(df_sum)
df_sum.plot.bar(subplots=True)
plt.show()

 

运行结果:

        2018年_pop  2018年_gdp     人均GDP
区域                                
东北      10836   56751.59  5.237319
中南      39627  246310.52  6.215725
华东      41172  345737.73  8.397399
华北      17522  119247.22  6.805571
西北      10279   51453.88  5.005728
西南      20217   95206.52  4.709231

         以上就是《Pandas统计分析基础(6):》,如果有改进的建议,欢迎在评论区留言交流~

        持续更新中......原创不易,各位看官请随手点下Follow和Star,感谢!!!

  • 12
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xlong~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值