﻿ 【Python】分组统计GroupBy技术详解 - 军军小站|张军博客

# 【Python】分组统计GroupBy技术详解

## 摘要

1.GroupBy过程

2.创建DataFrame

```            ```
import pandas as pd
ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',
'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],
'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],
'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}
df = pd.DataFrame(ipl_data)
df

```
```

3.将df按照Team列分组

```            ```
grouped = df.groupby('Team')
grouped

```
```

4.查看df按照Team分组之后结果

```            ```
grouped.groups

```
```

5.分组后的结果对Points求和

```            ```
grouped['Points'].sum()

```
```

6.根据任意长度适当的数组分组

```            ```
import numpy as np
key1 = np.array(list('abababbaaabb'))
df.groupby(key1).Team.count()

```
```

7.对分组进行迭代
GroupBy分组产生的是一组二元元组，有分组名和数据块组成。即(分组名、数据块)。

```            ```
for name,group in df.groupby('Team'):
print(name)
print(group)
print('*******分隔符*********')

```
```

```            ```
for (name1,name2),group in df.groupby(['Team','Rank']):
print(name1)
print(name2)
print(group)
print('*******分隔符*********')

```
```

8.在不同轴上分组
GroupBy默认是在axis=0轴上进行分组的，也可以在axis=1轴上进行分组聚合，不过用的相对较少。

```            ```
df.dtypes

```
```

```            ```
grouped = df.groupby(df.dtypes, axis=1)
grouped.groups

```
```

9.通过字典或Series进行分组

```            ```
people = pd.DataFrame(np.random.randn(5, 5),
columns=['a', 'b', 'c', 'd', 'e'],
index=['Joe', 'Steve', 'Wes', 'Jim','Travis'])
people.iloc[2:3, [1, 2]] = np.nan
people

```
```

```            ```
mapping = {'a': 'red', 'b': 'red', 'c': 'blue',
'd': 'blue', 'e': 'red', 'f' : 'orange'}
by_column = people.groupby(mapping, axis=1)
by_column.sum()

```
```

```            ```
map_series = pd.Series(mapping)
people.groupby(map_series, axis=1).count()

```
```

10.通过函数进行分组

```            ```
people.groupby(len).sum()

```
```

11.函数、数组、列表、字典、Series组合分组

```            ```
key_list = ['one', 'one', 'one', 'two', 'two']
people.groupby([len, key_list]).min()

```
```

12.根据索引级别分组

```            ```
df.columns = ([['a','a','a','b'],['Team', 'Rank', 'Year', 'Points']])
df.columns.names = ['one','two']
df

```
```

```            ```
df.groupby(level='one',axis=1).count()

```
```

12.多函数聚合

```            ```
df.columns = ['Team','Rank','Year','Points']
df.groupby('Team')['Points'].agg(['sum','mean','std'])

```
```

13.apply：一般性的“拆分-应用-合并”

```            ```
def top(df,n=2,column='Points'):
return df.sort_index(by=column,ascending=False)[:n]

```
```

```            ```
df.groupby('Team').apply(top)

```
```

```            ```
df.groupby('Team').apply(top,n=3)

```
```

QQ号联系： 360901061

【本文对您有帮助就好】