groupby()函数
1.根据列分组
就是根据这一列的值分组,有多少种值就分多少组。可以单列,也可以多列。
经过groupby后会生成一个groupby对象,该对象本身不会返回任何东西,只有当相应的方法被调用才会起作用。
grouped_single = df.groupby('School') # 根据一列的值分组
grouped_mul = df.groupby(['School', 'Class']) # 根据多列进行分组,列标签要用列表封起来
经过groupby后会生成一个groupby对象,该对象本身不会返回任何东西,只有当相应的方法被调用才会起作用。
比如下面要get_group():
print(grouped_single.get_group('S_1').head()) # get_group()方法传入分组依据的值,获取这个值对应的那个组
print(grouped_mul.get_group(('S_1', 'C_1'))) # 注意多列分组get_group时,传的参数要用tuple封起来
School Class ID Gender Address Height Weight Math Physics
0 S_1 C_1 1101 M street_1 173 63 34.0 A+
1 S_1 C_1 1102 F street_2 192 73 32.5 B+
2 S_1 C_1 1103 M street_2 186 82 87.2 B+
3 S_1 C_1 1104 F street_2 167 81 80.4 B-
4 S_1 C_1 1105 F street_4 159 64 84.8 B+
School Class ID Gender Address Height Weight Math Physics
0 S_1 C_1 1101 M street_1 173 63 34.0 A+
1 S_1 C_1 1102 F street_2 192 73 32.5 B+
2 S_1 C_1 1103 M street_2 186 82 87.2 B+
3 S_1 C_1 1104 F street_2 167 81 80.4 B-
4 S_1 C_1 1105 F street_4 159 64 84.8 B+
2.获取组容量和组数
使用size()方法,注意是方法,不是属性。
会返回一个Series,index是分组依据的值,values是这个组有多少元素。
使用ngroups属性,直接返回组数.
print(grouped_single.size(), '\n')
print(grouped_mul.size(), '\n')
School
S_1 15
S_2 20
dtype: int64
School Class
S_1 C_1 5
C_2 5
C_3 5
S_2 C_1 5
C_2 5
C_3 5
C_4 5
dtype: int64
print(grouped_single.ngroups, grouped_mul.ngroups)
2 7
3.组的遍历
遍历的临时变量有两个,第一个是组名【就是分组依据的那个值】,第二个就是整个分组后的group。
for name, group in grouped_single:
print(name + ':')
print(group.head(), '\n')
S_1:
School Class ID Gender Address Height Weight Math Physics
0 S_1 C_1 1101 M street_1 173 63 34.0 A+
1 S_1 C_1 1102 F street_2 192 73 32.5 B+
2 S_1 C_1 1103 M street_2 186 82 87.2 B+
3 S_1 C_1 1104 F street_2 167 81 80.4 B-
4 S_1 C_1 1105 F street_4 159 64 84.8 B+
S_2:
School Class ID Gender Address Height Weight Math Physics
15 S_2 C_1 2101 M street_7 174 84 83.3 C
16 S_2 C_1 2102 F street_6 161 61 50.6 B+
17 S_2 C_1 2103 M street_4 157 61 52.5 B-
18 S_2 C_1 2104 F street_5 159 97 72.2 B+
19 S_2 C_1 2105 M street_4 170 81 34.2 A
# 下面的方式遍历的group是一个tuple,有两个元素,一个就是name,一个就是真的group
# for group in grouped_single:
# print(group)
4.level参数
还没看