In [1]:
import seaborn as sns

titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age', 'sex', 'class', 'fare', 'survived']]
print(df.shape)
df.head()
(891, 5)
Out[1]:
age sex class fare survived
0 22.0 male Third 7.2500 0
1 38.0 female First 71.2833 1
2 26.0 female Third 7.9250 1
3 35.0 female First 53.1000 1
4 35.0 male Third 8.0500 0
In [2]:
# 'class' 열의 값 기준으로 그룹화
grouped = df.groupby(['class'])
grouped
Out[2]:
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x00000181AD715248>
In [3]:
# 사용자 정의 함수를 집계 함수로 쓰고 싶음
def min_max(series):
    return series.max() - series.min()  # 최대값 - 최소값
In [4]:
# min_max 함수를 사용해서 집계
grouped[['age', 'fare']].agg(min_max)
Out[4]:
age fare
class
First 79.08 512.3292
Second 69.33 73.5000
Third 73.58 69.5500
In [5]:
# 여러 함수를 동시에 적용. pandas 의 기본 함수 사용 가능
grouped[['age', 'fare']].agg(['max', 'min', min_max])
Out[5]:
age fare
max min min_max max min min_max
class
First 80.0 0.92 79.08 512.3292 0.0 512.3292
Second 70.0 0.67 69.33 73.5000 0.0 73.5000
Third 74.0 0.42 73.58 69.5500 0.0 69.5500
In [6]:
# 열별로 다른 함수 적용
grouped.agg({'age': 'mean', 'fare': ['max', 'min']})
Out[6]:
age fare
mean max min
class
First 38.233441 512.3292 0.0
Second 29.877630 73.5000 0.0
Third 25.140620 69.5500 0.0