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)

运行结果:

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))

运行结果:

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]

  1. 数据聚合方法

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

  1. 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()

Pandas统计分析基础(6):基于groupby的数据分组和分组后的数据可视化&数据聚合方法(agg/apply/transform方法)
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')

Pandas统计分析基础(6):基于groupby的数据分组和分组后的数据可视化&数据聚合方法(agg/apply/transform方法)
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):基于groupby的数据分组和分组后的数据可视化&数据聚合方法(agg/apply/transform方法)

以上就是《Pandas统计分析基础(6):》,如果有改进的建议,欢迎在评论区留言交流~
持续更新中……原创不易,各位看官请随手点下Follow和Star,感谢!!!

Original: https://blog.csdn.net/l1796333514/article/details/123692897
Author: Xlong~
Title: Pandas统计分析基础(6):基于groupby的数据分组和分组后的数据可视化&数据聚合方法(agg/apply/transform方法)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/639956/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 荣耀智慧屏x1和红米x65哪个好

    Redmi智能电视X65采用金属边框,荣耀智慧屏X1为塑料边框。全金属超窄边框,不仅视野边界再次拓展,金属品质感更使整机沉稳大气,百搭现代家居环境!荣耀智慧屏X1更多使用感受和评价…

    人工智能 2023年5月27日
    084
  • PPT分享:搜索引擎如何理解用户意图

    简介 本文主要介绍著名的搜索算法工程师 Trey Grainger 在2019年的PPT分享。PPT分享的标题是《Balancing the Dimensions of User …

    人工智能 2023年6月1日
    078
  • Object Detection in 20 Years: A Survey 20年间的目标检测:综述

    摘要 物体检测作为计算机视觉中最基本和最具挑战性的问题之一,近年来受到了极大的关注。它在过去二十年中的发展可以看作是计算机视觉历史的缩影。如果我们把今天的物体探测看成是深度学习力量…

    人工智能 2023年7月9日
    053
  • 【Java】反射, 枚举,Lambda表达式

    ✨系列专栏: 【Java SE】✨一句短话:难在坚持,贵在坚持,成在坚持! 文章目录 一. 反射 * 1. 反射的概述 2. 反射的使用 – 2.1 反射常用的类 2….

    人工智能 2023年7月29日
    062
  • Python-OpenCV对图像的遍历操作示例代码

    Python-OpenCV对图像像素的遍历操作示例 如果您想了解OpenCV-C++是如何遍历图像像图的,那么可以参看下面这个页面:https://www.hhai.cc/thre…

    人工智能 2023年7月18日
    051
  • One-shot就能做事件抽取?ChatGPT在信息抽取上的强大应用

    One-shot就能做事件抽取?ChatGPT在信息抽取上的强大应用 0. 前言 1. 灵感 2. 实验 3. 结论 前言 近期,OpenAI发布的chat GPT可谓是各种刷屏,…

    人工智能 2023年7月31日
    070
  • 通过Django实现图像识别

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 一、训练模型 二、 使用模型并预测 三、通过django实现图像识别 该项目需要用到的标准库有: ope…

    人工智能 2023年5月26日
    0103
  • Apollo Cyber RT简介

    Apollo Cyber RT是世界上第一个专为自动驾驶定制的一个开源、高性能的运行框架。它为自动驾驶场景而设计,并针对自动驾驶的高并发、低延迟、高吞吐量进行了大幅优化。 作为百度…

    人工智能 2023年6月2日
    063
  • python之OCR文字识别

    将图片翻译成文字一般被称为光学文字识别(Optical Character Recognition,OCR)。可以实现OCR 的底层库并不多,目前很多库都是使用共同的几个底层OCR…

    人工智能 2023年7月4日
    0117
  • DQN(deep Q-network)算法简述

    本文通过整理李宏毅老师的机器学习教程的内容,简要介绍深度强化学习(deep reinforcement learning)中的 DQN(deep Q-network)算法。 李宏毅…

    人工智能 2023年6月22日
    060
  • tensorboard可视化

    tensorboard可视化 Tensorboard导入与可视化图片 模型网络结构的可视化 标量数据的可视化 Tensorboard导入与可视化图片 以手写数字分类mnist数据集…

    人工智能 2023年6月16日
    065
  • CNCC——多模态会议

    一.多模态语义理解 1.视觉与语言生成 1.1 语义鸿沟和异构鸿沟 但如果解决好这两大科学问题,就会多出来一些有用信息,来做到一些只用图像做不到的事情是有可能的。 比如加上一些文本…

    人工智能 2023年5月28日
    0126
  • Arithmetic Operations(分类暴力dp)

    给你一个数组a a a,每次操作可以选择一个a i a_i a i ​将其变成任意一个数x x x,问你最少操作多少次使之变成一个等差数列。 ​ 不好判断修改哪几个数,但是哪些数不…

    人工智能 2023年7月2日
    082
  • YOLOv5尝试修改backbone

    本博文记录第一次修改yolov5,只是尝试,不做工程效率的考虑 最近尝试修改yolov5的网络结构,在这里记录一下 第一步:加入模块代码 将模型搭建中所需的模块放入YOLOv5的源…

    人工智能 2023年7月21日
    065
  • YOLO系列详解 目标检测

    yolo v1 前言 相比同年的fast-rcnn和ssd都没有优势 ; 详解 B=2,Pr(Object)为0或者1 在v1中没有anchor的概念,预测的xywh是直接预测的b…

    人工智能 2023年7月10日
    096
  • 【python | linux10】面向对象四大特征(抽象、封装、继承、多态)详解

    ### 回答1: Java是一种 面向对象_的编程 _语言,它支持 封装、 继承_和 _多态_等特性。 _封装_是指将数据和方法 _封装_在一个类中,以保护数据的安全性和完整性。 …

    人工智能 2023年7月6日
    053
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球