20 Groupby Aggregation
| 6 Minute Read on Pandas
GroupBy Aggregate¶
- Groupby 객체의 Aggregate 메소드 docs 는 그룹함수들을 수집하여 한번에 처리하는 기능으로 DataFrameGroupBy.agg(arg, * args, kwargs)로 표현된다.
- args에 string, tuple, dicionary, list 를 입력할 수 있다.
Agg(Aggregate) 메소드는 다음 용도로 사용된다.
- count, sum, mean, min, max, first, last같은 그룹함수를 동시에 사용할 경우에
- 자신만의 데이터 집계함수를 사용하기 위해(즉, 사용자 집계함수)
Agg를 사용하는 대표적인 표현으로는 컬럼과 적용 집계함수를 딕셔너리로 만들고 그 딕셔너리를 튜플로 만들어 Agg메소드의 인자로 넣는 방법이다.
- ex) tuple_dic = {2000:['count','mean'], 2001:['max']}
- ex) df.groupby(['Team','Season']).agg(tuple_dic)
In [1]:
import numpy as np
import pandas as pd
arrays = [['Arizona','Boston','Chicago','Detroit', 'Arizona','Boston','Chicago','Detroit']
,['First','First','First','First','Second','Second','Second','Second']]
index = pd.MultiIndex.from_arrays(arrays, names=('City','Season'))
columns = [2003, 2004, 2005]
#df = pd.DataFrame(np.random.randn(8, 3), index=index, columns = columns)
df = pd.DataFrame(np.arange(24).reshape((-1, 3)), index=index, columns = columns)
df
Out[1]:
In [2]:
# dictionary의 tuple을 인자로 사용
tu_dic = {2003:['count','mean'], 2004:['max']}
df.groupby(['Season']).agg(tu_dic)
Out[2]:
In [3]:
# columns의 값들에 조건을 추가
tu_dic = {2003:['count','mean'], 2004:['max']}
df[(df[2003]>5) & (df[2004]>3)].groupby(['Season']).agg(tu_dic)
Out[3]:
In [4]:
# reset_index을 사용하여 index를 columns을 변경할 수 있음
tu_dic = {2003:['count','mean'], 2004:['max']}
df.groupby(['Season']).agg(tu_dic)
Out[4]:
In [5]:
#groupby를 사용하며 컬럼과 집계합수로 분류가 되므로 멀터인덱스가 생성된다.
#droplevel() 을 사용하여 멀티인덱스중에 컬럼명을 제거
gpby = df.groupby(['Season']).agg(tu_dic)
gpby.columns = gpby.columns.droplevel()
gpby
Out[5]:
In [6]:
# Index객체의 속성을 사용하여 컬럼과 집계수함수의 이름을 하나로 축약할 수 도 있다.
gpby = df.groupby(['Season']).agg(tu_dic).reset_index()
gpby.columns = pd.Index([str(e[0])+ '_'+ e[1] for e in gpby.columns.tolist()])
gpby
Out[6]: