logo

[python-ds] 판다스: 그룹핑

import pandas as pd
 

census.xlsx 파일 열기

df = pd.read_excel('census.xlsx')
df.head()
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
039State-gov77516Bachelors13Never-marriedAdm-clericalNot-in-familyWhiteMale2174040United-States<=50K
150Self-emp-not-inc83311Bachelors13Married-civ-spouseExec-managerialHusbandWhiteMale0013United-States<=50K
238Private215646HS-grad9DivorcedHandlers-cleanersNot-in-familyWhiteMale0040United-States<=50K
353Private23472111th7Married-civ-spouseHandlers-cleanersHusbandBlackMale0040United-States<=50K
428Private338409Bachelors13Married-civ-spouseProf-specialtyWifeBlackFemale0040Cuba<=50K
 

소득 수준에 따라 그룹짓기

g1 = df.groupby('income')
 

그룹 보기

g1.groups
{'<=50K': Int64Index([    0,     1,     2,     3,     4,     5,     6,    12,    13,
                15,
             ...
             32548, 32549, 32550, 32551, 32552, 32553, 32555, 32556, 32558,
             32559],
            dtype='int64', length=24720),
 '>50K': Int64Index([    7,     8,     9,    10,    11,    14,    19,    20,    25,
                27,
             ...
             32530, 32532, 32533, 32536, 32538, 32539, 32545, 32554, 32557,
             32560],
            dtype='int64', length=7841)}
 

특정 그룹만 보기

g1.get_group('>50K').head()
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
752Self-emp-not-inc209642HS-grad9Married-civ-spouseExec-managerialHusbandWhiteMale0045United-States>50K
831Private45781Masters14Never-marriedProf-specialtyNot-in-familyWhiteFemale14084050United-States>50K
942Private159449Bachelors13Married-civ-spouseExec-managerialHusbandWhiteMale5178040United-States>50K
1037Private280464Some-college10Married-civ-spouseExec-managerialHusbandBlackMale0080United-States>50K
1130State-gov141297Bachelors13Married-civ-spouseProf-specialtyHusbandAsian-Pac-IslanderMale0040India>50K
 

그룹별 통계

import numpy as np
df['education_num'].mean()  # 전체 평균
10.0806793403151
g1['education_num'].mean()
income
<=50K     9.595065
>50K     11.611657
Name: education_num, dtype: float64
g1['education_num'].describe()
countmeanstdmin25%50%75%max
income
<=50K24720.09.5950652.4361471.09.09.010.016.0
>50K7841.011.6116572.3851292.010.012.013.016.0
 

nth

g1['capital_gain'].nth(0)
income
<=50K    2174
>50K        0
Name: capital_gain, dtype: int64
g1['capital_gain'].nth(-1)
income
<=50K        0
>50K     15024
Name: capital_gain, dtype: int64
 

agg

aggregate: 모으다(모아서 정리하다)

g1.agg({'education_num': np.mean})
education_num
income
<=50K9.595065
>50K11.611657
 

그룹별 education_num 평균과 표준편차

g1.agg({'education_num': [np.mean, np.std]})
education_num
meanstd
income
<=50K9.5950652.436147
>50K11.6116572.385129
 

그룹별 capital_gain 평균

g1.agg({'capital_gain': np.mean})
capital_gain
income
<=50K148.752468
>50K4006.142456
 

모두 적용

g1.agg(
    {
        'education_num': [np.mean, np.std],
        'capital_gain': np.mean
    }
)
education_numcapital_gain
meanstdmean
income
<=50K9.5950652.436147148.752468
>50K11.6116572.3851294006.142456
 

실습

성별(sex)에 따라 education_num의 평균(np.mean)과 표준편차(np.std)를 구하세요.

SELECT AVG(eduation_num), STD(education_num) FROM df GROUP BY sex;
df.groupby('sex').agg({'education_num': [np.mean, np.std]})
education_num
meanstd
sex
Female10.0357442.379954
Male10.1028912.662630
 

race와 income으로 그룹

g2 = df.groupby(['race', 'income'])
rie = g2.agg({'education_num': np.mean})
rie.to_excel('rie.xlsx')
rie
education_num
raceincome
Amer-Indian-Eskimo<=50K9.061818
>50K11.222222
Asian-Pac-Islander<=50K10.440367
>50K12.398551
Black<=50K9.261235
>50K11.077519
Other<=50K8.560976
>50K11.600000
White<=50K9.627422
>50K11.612196
 

reset_index

rie.reset_index()
raceincomeeducation_num
0Amer-Indian-Eskimo<=50K9.061818
1Amer-Indian-Eskimo>50K11.222222
2Asian-Pac-Islander<=50K10.440367
3Asian-Pac-Islander>50K12.398551
4Black<=50K9.261235
5Black>50K11.077519
6Other<=50K8.560976
7Other>50K11.600000
8White<=50K9.627422
9White>50K11.612196
 

unique

컬럼에 포함된 값의 종류를 알려준다.

df['race'].unique()
array(['White', 'Black', 'Asian-Pac-Islander', 'Amer-Indian-Eskimo',
       'Other'], dtype=object)
 

category

범주형 데이터의 경우 기본적으로 object 형으로 되어 있으나 pandascategory 형으로 변환하면 메모리를 절약하고 속도를 높일 수 있다.

df['age'].dtype
dtype('int64')
df['age'].memory_usage()
260568
df['age'].astype('int16').memory_usage()
65202
df['race'].dtype
dtype('O')
df['race'].memory_usage()
260616
race = df['race'].astype('category')
race.dtype
CategoricalDtype(categories=['Amer-Indian-Eskimo', 'Asian-Pac-Islander', 'Black', 'Other',
                  'White'],
                 ordered=False)
race.memory_usage()
32889
Previous
텐서플로 기초