edwith_python_(6)건강검진데이터 살펴보기

Updated:

edwith 부스트코스 파이썬으로 시작하는 데이터 사이언스 를 공부하는 과정입니다.

지난 포스트 :point_right: edwith_python_(5)위도, 경도 데이터를 이용하여 지도에 나타내기


이번 포스트 부터는 공공 데이터 포털의 2017년 건강검진 데이터 활용! 다운로드 받기

데이터 분석을 하기 전에 가설을 세워보자.

가설

* 음주 여부에 따라 건강검진 수치 차이가 있을까?  
* 신장과 허리둘레의 크기는 체중과 상관관계가 있을까?

1. 라이브러리 로드

분석에 사용할 라이브러리 불러오기
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

2. 한글폰트 설정

#google colab에서 한글을 그래프에 표현하려면 아래의 설정이 필요!

import matplotlib as mpl

#한글 깨지지 않도록 설정
!apt -qq -y install fonts-nanum > /dev/null

import matplotlib.font_manager as fm

fontpath = '/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf'
font = fm.FontProperties(fname=fontpath, size=9)
fm._rebuild ()

plt.rc('font', family='NanumBarunGothic') 
plt.rc("axes", unicode_minus=False)

#글씨가 선명하게 보이도록 설정
%config InlineBackend.figure_format = 'retina'

3. 데이터 불러오기

구글 드라이브 마운트
from google.colab import drive
drive.mount('/content/drive')
분석할 데이터를 df 변수로 지정하여 불러오기
df = pd.read_csv("/content/drive/My Drive/colab/edwith_study/건강검진정보_2017.csv", encoding="cp949")

encoding=”cp949” 한글 인코딩 된 파일 불러올 때 사용

4. 기본 정보 보기

info를 통해 기본 정보 보기
df.info()

*결과*

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000000 entries, 0 to 999999
Data columns (total 34 columns):
 #   Column        Non-Null Count    Dtype  
---  ------        --------------    -----  
 0   기준년도          1000000 non-null  int64  
 1   가입자일련번호       1000000 non-null  int64  
 2   성별코드          1000000 non-null  int64  
 3   연령대코드(5세단위)   1000000 non-null  int64  
 4   시도코드          1000000 non-null  int64  
 5   신장(5Cm단위)     1000000 non-null  int64  
 6   체중(5Kg단위)     1000000 non-null  int64  
 7   허리둘레          999734 non-null   float64
 8   시력(좌)         999817 non-null   float64
 9   시력(우)         999811 non-null   float64
 10  청력(좌)         999842 non-null   float64
 11  청력(우)         999844 non-null   float64
 12  수축기혈압         999981 non-null   float64
 13  이완기혈압         999982 non-null   float64
 14  식전혈당(공복혈당)    999958 non-null   float64
 15  총콜레스테롤        999957 non-null   float64
 16  트리글리세라이드      999955 non-null   float64
 17  HDL콜레스테롤      999956 non-null   float64
 18  LDL콜레스테롤      997088 non-null   float64
 19  혈색소           999948 non-null   float64
 20  요단백           995408 non-null   float64
 21  혈청크레아티닌       999957 non-null   float64
 22  (혈청지오티)AST    999959 non-null   float64
 23  (혈청지오티)ALT    999958 non-null   float64
 24  감마지티피         999958 non-null   float64
 25  흡연상태          999856 non-null   float64
 26  음주여부          999464 non-null   float64
 27  구강검진수검여부      1000000 non-null  int64  
 28  치아우식증유무       0 non-null        float64
 29  결손치유무         0 non-null        float64
 30  치아마모증유무       0 non-null        float64
 31  제3대구치(사랑니)이상  0 non-null        float64
 32  치석            400523 non-null   float64
 33  데이터공개일자       1000000 non-null  int64  
dtypes: float64(25), int64(9)
memory usage: 259.4 MB
컬럼명만 출력하기
df.columns

*결과*

Index(['기준년도', '가입자일련번호', '성별코드', '연령대코드(5세단위)', '시도코드', '신장(5Cm단위)',
       '체중(5Kg단위)', '허리둘레', '시력(좌)', '시력(우)', '청력(좌)', '청력(우)', '수축기혈압',
       '이완기혈압', '식전혈당(공복혈당)', '총콜레스테롤', '트리글리세라이드', 'HDL콜레스테롤', 'LDL콜레스테롤',
       '혈색소', '요단백', '혈청크레아티닌', '(혈청지오티)AST', '(혈청지오티)ALT', '감마지티피', '흡연상태',
       '음주여부', '구강검진수검여부', '치아우식증유무', '결손치유무', '치아마모증유무', '제3대구치(사랑니)이상', '치석',
       '데이터공개일자'],
      dtype='object')
데이터 형식만 출력하기
df.dtypes

*결과*

기준년도              int64
가입자일련번호           int64
성별코드              int64
연령대코드(5세단위)       int64
시도코드              int64
신장(5Cm단위)         int64
체중(5Kg단위)         int64
허리둘레            float64
시력(좌)           float64
시력(우)           float64
청력(좌)           float64
청력(우)           float64
수축기혈압           float64
이완기혈압           float64
식전혈당(공복혈당)      float64
총콜레스테롤          float64
트리글리세라이드        float64
HDL콜레스테롤        float64
LDL콜레스테롤        float64
혈색소             float64
요단백             float64
혈청크레아티닌         float64
(혈청지오티)AST      float64
(혈청지오티)ALT      float64
감마지티피           float64
흡연상태            float64
음주여부            float64
구강검진수검여부          int64
치아우식증유무         float64
결손치유무           float64
치아마모증유무         float64
제3대구치(사랑니)이상    float64
치석              float64
데이터공개일자           int64
dtype: object

5. 결측치 보기

컬럼별 결측치 개수 알아보기
df.isnull().sum()

*결과*

기준년도                  0
가입자일련번호               0
성별코드                  0
연령대코드(5세단위)           0
시도코드                  0
신장(5Cm단위)             0
체중(5Kg단위)             0
허리둘레                266
시력(좌)               183
시력(우)               189
청력(좌)               158
청력(우)               156
수축기혈압                19
이완기혈압                18
식전혈당(공복혈당)           42
총콜레스테롤               43
트리글리세라이드             45
HDL콜레스테롤             44
LDL콜레스테롤           2912
혈색소                  52
요단백                4592
혈청크레아티닌              43
(혈청지오티)AST           41
(혈청지오티)ALT           42
감마지티피                42
흡연상태                144
음주여부                536
구강검진수검여부              0
치아우식증유무         1000000
결손치유무           1000000
치아마모증유무         1000000
제3대구치(사랑니)이상    1000000
치석               599477
데이터공개일자               0
dtype: int64

df.isna().sum() 과 같음

pandas를 통해 결측치 시각화하기
df.isnull().sum().plot.barh(figsize=(7,9))

*결과*

6. 일부 데이터 요약하기

“(혈청지오티)ALT”, “(혈청지오티)AST” 컬럼 값을 가져와서 미리보기
df[["(혈청지오티)ALT", "(혈청지오티)AST"]].head()

*결과*

  (혈청지오티)ALT (혈청지오티)AST
0 35.0 21.0
1 36.0 20.0
2 32.0 47.0
3 34.0 29.0
4 12.0 19.0

2개 이상의 컬럼값을 불러올 때는 데이터프레임 형식으로 불러와야함. (대괄호 두개)
시리즈 형식(대괄호 하나)으로 불러오면 keyerror 발생

“(혈청지오티)ALT”, “(혈청지오티)AST” 요약하기
df[["(혈청지오티)ALT", "(혈청지오티)AST"]].describe()

*결과*

  (혈청지오티)ALT (혈청지오티)AST
count 999958.000000 999959.000000
mean 25.749509 25.994671
std 26.294770 23.587469
min 1.000000 1.000000
25% 15.000000 19.000000
50% 20.000000 23.000000
75% 29.000000 28.000000
max 7210.000000 9999.000000

7. value_counts 로 값 집계하기

value_counts를 통해 성별코드로 그룹화하여 개수 카운팅
df["성별코드"].value_counts()

*결과*

1    530410
2    469590
Name: 성별코드, dtype: int64
value_counts를 통해 흡연상태로 그룹화하여 개수 카운팅
df["흡연상태"].value_counts()

*결과*

1.0    607942
3.0    215702
2.0    176212
Name: 흡연상태, dtype: int64

다음 포스트 :point_right: edwith_python_(7)groupby 와 pivot_table 사용하기

Categories:

Updated:

Leave a comment