10-3 apply 메서드 활용하기 - 고급
이번에는 조금 더 큰 데이터를 사용하여 실습을 진행해 보겠다. 이번에 사용할 데이터는 seaborn 라이브러리의 titanic 데이터 집합이다.
In [8]:
import seaborn as sns
titanic = sns.load_dataset("titanic")
다음은 titanic 데이터프레임의 데이터 정보를 출력한 것이다.¶
In [9]:
print(titanic.info( ))
<class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object 3 age 714 non-null float64 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null float64 7 embarked 889 non-null object 8 class 891 non-null category 9 who 891 non-null object 10 adult_male 891 non-null bool 11 deck 203 non-null category 12 embark_town 889 non-null object 13 alive 891 non-null object 14 alone 891 non-null bool dtypes: bool(2), category(2), float64(2), int64(4), object(5) memory usage: 80.7+ KB None
다음은 누락값의 개수를 반환하는 count_missing 함수이다. 판다스의 isnull 메서드에 데이터프레임을 전달하면 누락값 유무에 따라 True, False를 적용한 데이터프레임이 만들어진다. 이 값을 넘파이의 sum 메서드에 전달하면 누락값의 개수를 구할 수 있다.¶
In [11]:
import numpy as np
def count_missing(vec):
null_vec = pd.isnull(vec)
null_count = np.sum(null_vec)
return null_count
다음은 apply 메서드에 count_missing 함수를 전달하여 얻은 결과이다.¶
In [13]:
import pandas as pd
cmis_col = titanic.apply(count_missing)
print(cmis_col)
survived 0 pclass 0 sex 0 age 177 sibsp 0 parch 0 fare 0 embarked 2 class 0 who 0 adult_male 0 deck 688 embark_town 2 alive 0 alone 0 dtype: int64
다음은 누락값의 비율을 계산하는 prop_missing 함수이다. 과정 3에서 작성한 count_missing 함수를 이용해 데이터프레임의 누락값 개수를 구하고 size 속성을 이용해 데이터프레임의 전체 데이터 수를 구하여 나누면 누락값의 비율을 계산할 수 있다.¶
In [14]:
def prop_missing(vec):
num = count_missing(vec)
dem = vec.size
return num / dem
다음은 apply 메서드에 prop_missing 함수를 적용한 것이다.¶
In [15]:
pmis_col = titanic.apply(prop_missing)
print(pmis_col)
survived 0.000000 pclass 0.000000 sex 0.000000 age 0.198653 sibsp 0.000000 parch 0.000000 fare 0.000000 embarked 0.002245 class 0.000000 who 0.000000 adult_male 0.000000 deck 0.772166 embark_town 0.002245 alive 0.000000 alone 0.000000 dtype: float64
과정 5에서 작성한 prop_missing 함수를 이용하면 누락값이 아닌 데이터의 비율도 구할 수 있다. 전체 비율(1)에서 누락값의 비율을 뺴면 된다. 과정 5~6과 같은 방법으로 apply 메서드에 prop_complete 함수를 전달하여 결과를 확인해 보자.¶
In [17]:
def prop_complete(vec):
return 1 - prop_missing(vec)
데이터프레임의 누락값 처리하기 - 행 방향¶
이번에는 행 방향으로 데이터를 처리해 보겠다. 다음은 axis를 1로 설정하여 앞에서 만든 count_missing, prop_missing, prop_complete 함수를 행 방향으로 적용하여 실행한 것이다. 각 행의 누락값과 누락값의 비율, 누락값이 아닌 값의 비율을 잘 계산하고 있다는 것을 알 수 있다.
In [18]:
cmis_row = titanic.apply(count_missing, axis=1)
pmis_row = titanic.apply(prop_missing, axis=1)
pcom_row = titanic.apply(prop_complete, axis=1)
In [20]:
print(cmis_row.head())
0 1 1 0 2 1 3 0 4 1 dtype: int64
In [21]:
print(pmis_row.head())
0 0.066667 1 0.000000 2 0.066667 3 0.000000 4 0.066667 dtype: float64
In [22]:
print(pcom_row.head())
0 0.933333 1 1.000000 2 0.933333 3 1.000000 4 0.933333 dtype: float64
다음은 누락값의 개수를 구하여 titanic 데이터프레임에 추가한 것이다. 데이터프레임에 num_missing 열이 추가된 것을 알 수 있다.¶
In [23]:
titanic['num_missing'] = titanic.apply(count_missing, axis=1)
print(titanic.head())
survived pclass sex age sibsp parch fare embarked class \ 0 0 3 male 22.0 1 0 7.2500 S Third 1 1 1 female 38.0 1 0 71.2833 C First 2 1 3 female 26.0 0 0 7.9250 S Third 3 1 1 female 35.0 1 0 53.1000 S First 4 0 3 male 35.0 0 0 8.0500 S Third who adult_male deck embark_town alive alone num_missing 0 man True NaN Southampton no False 1 1 woman False C Cherbourg yes False 0 2 woman False NaN Southampton yes True 1 3 woman False C Southampton yes False 0 4 man True NaN Southampton no True 1
위 과정에서 누락값이 있는 데이터를 데이터프레임에 추가했기 때문에 누락값이 있는 데이터만 따로 모아서 볼 수도 있다. 다음은 누락값이 2개 이상인 데이터를 추출한 것이다.¶
In [29]:
print(titanic.loc[titanic.num_missing > 1, :].sample(10))
survived pclass sex age sibsp parch fare embarked class \ 611 0 3 male NaN 0 0 7.0500 S Third 709 1 3 male NaN 1 1 15.2458 C Third 888 0 3 female NaN 1 2 23.4500 S Third 48 0 3 male NaN 2 0 21.6792 C Third 354 0 3 male NaN 0 0 7.2250 C Third 778 0 3 male NaN 0 0 7.7375 Q Third 301 1 3 male NaN 2 0 23.2500 Q Third 428 0 3 male NaN 0 0 7.7500 Q Third 470 0 3 male NaN 0 0 7.2500 S Third 375 1 1 female NaN 1 0 82.1708 C First who adult_male deck embark_town alive alone num_missing 611 man True NaN Southampton no True 2 709 man True NaN Cherbourg yes False 2 888 woman False NaN Southampton no False 2 48 man True NaN Cherbourg no False 2 354 man True NaN Cherbourg no True 2 778 man True NaN Queenstown no True 2 301 man True NaN Queenstown yes False 2 428 man True NaN Queenstown no True 2 470 man True NaN Southampton no True 2 375 woman False NaN Cherbourg yes False 2
마무리하며
이 장에서는 여러 가지 실습을 통해 apply 메서드가 왜 데이터 분석에 유용한지 알아보았다. 내장 함수의 기능도 훌륭하지만 때로는 나만의 함수를 만들어 데이터 처리에 사용하는 것이 더 편리할 수도 있기 때문에 apply 메서드의 사용법은 반드시 알아두어야 한다.
출처 : Do it! 데이터 분석을 위한 판다스
'Python > Pandas' 카테고리의 다른 글
<파이썬 판다스> Chapter 11-2 데이터 변환 (0) | 2023.05.19 |
---|---|
<파이썬 판다스> Chapter 11-1 데이터 집계 (0) | 2023.05.17 |
<파이썬 판다스> Chapter 10-2 apply 메서드 활용하기 - 기초 (0) | 2023.05.14 |
<파이썬 판다스> Chapter 10-1 간단한 함수 만들기 (0) | 2023.05.14 |
<파이썬 판다스> Chapter 09-4 정규식으로 문자열 처리에 날개 달기 (0) | 2023.05.14 |