数据分组
★ 使用 groupby() 方法进行分组
★ group.size()查看分组后每组的数量
★ group.groups 查看分组情况
★ group.get_group(“名字”) 根据分组后的名字选择分组数据
首先打开一份数据
使用 groupby() 方法进行分组
可以按 性别 进行分组,或者同时按 性别 和 婚姻状况 来分组
使用groupby的size方法可以查看分组后每组的数量, 并返回一个含有分组大小的Series
按性别分组:假如我想看男的有多少人?女的有多少人?
1 2 3 4 5 6 7 8 | import pandas as pd pd.set_option( 'display.unicode.ambiguous_as_wide' , True ) #处理数据的列标题与数据无法对齐的情况 pd.set_option( 'display.unicode.east_asian_width' , True ) #无法对齐主要是因为列标题是中文 df = pd.read_excel(r 'C:\Users\Administrator\Desktop\python练习\xbx_stock_2019\People.xls' ,encoding = 'gbk' ) df1 = df.groupby( '性别' ).size() print (df1) |
同时按 性别 和 婚姻状况 分组:
1 | df.groupby([ '性别' , '婚姻状况' ]).size() |
对分组进行遍历
将分组后的对象进行遍历,可以获取到每个组的名字以及每个组的数据
例如我将上面的数据按照 性别 分组,它返回的是一个对象,结果是这样的:
1 | <pandas.core.groupby.generic.DataFrameGroupBy object at 0x00000000028FCBE0 > |
我们看不到里面的内容,如果想要里面有什么内容可以使用for循环把里面的数据遍历出来
01 02 03 04 05 06 07 08 09 10 11 12 | import pandas as pd pd.set_option( 'display.unicode.ambiguous_as_wide' , True ) #处理数据的列标题与数据无法对齐的情况 pd.set_option( 'display.unicode.east_asian_width' , True ) #无法对齐主要是因为列标题是中文 df = pd.read_excel(r 'C:\Users\Administrator\Desktop\python练习\xbx_stock_2019\People.xls' ,encoding = 'gbk' ) group = df.groupby( '性别' ) for df_name,df_DataFrame in group: print (df_name) print (df_DataFrame) |
这样就能看到分组后的对象信息了
现在我有一个这样的需求,我想知道,分组后,各组的年龄最大值、最小值和平均值,需要怎么做呢?
方法如下:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | import pandas as pd pd.set_option( 'display.unicode.ambiguous_as_wide' , True ) #处理数据的列标题与数据无法对齐的情况 pd.set_option( 'display.unicode.east_asian_width' , True ) #无法对齐主要是因为列标题是中文 df = pd.read_excel(r 'C:\Users\Administrator\Desktop\python练习\xbx_stock_2019\People.xls' ,encoding = 'gbk' ) group = df.groupby( '性别' ) for df_name,df_age in group: df_max = df_age[ '年龄' ]. max () df_min = df_age[ '年龄' ]. min () df_mean = df_age[ '年龄' ].mean() print (f '{df_name}性的最大年龄是:{df_max},最小年龄是:{df_min},平均年龄是:{df_mean}' ) |