더보기

데이터 분석 절차

  1. 데이터 읽기 : 데이터를 불러오고 Dataframe 구조를 확인
  2. 데이터 정제 : 데이터 형 변환 및 결측값과 이상치 처리
  3. 데이터 시각화 : 각 변수 별로 추가적인 정제 또는 feature engineering 과정을 거치고 시각화를 통해 데이터 특성 파악

 

1. 데이터 읽기

1.1 데이터 불러오기

: csv 파일을 dataframe 형태로 읽어온다.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_csv("./data.csv")

1.2 데이터 확인

df.head()	# 상위 5개 데이터 출력
df.tail(7)	# 하위 7개 데이터 출력
df.shape()	# 몇 행과 몇 열인지 출력
df.info()	# dataframe 정보 요약하여 출력
df.describe(include='all')	# include='all':카테고리형 변수도 정보 제공 (생략가능)

len(list(set(df['col1'])))	# col1 데이터 개수 확인
sorted(list(set(df['col1'])))	# col1 데이터 중복없이 오름차순 정렬 후 확인

 

2. 데이터 정제

2.1 결측값 확인 후 제거 및 대체

  • 결측값 확인
# 각 열 별로 결측치의 갯수를 반환 (True:1, False:0)
df.isna().sum()
df.isnull().sum()

# 전체 결측값의 수
df.isnull().sum().sum()
  • 결측값이 많지 않은 경우 결측값 삭제
# 결측값이 있는 column 삭제
df_del_col = df.drop(columns = ['col5', 'col6'])

# 사용하려는 변수의 데이터에서 결측값이 아닌 부분을 골라내어 저장
df_clean = df[~df['col1'].isnull()]
  • 결측값이 많은 경우 특정 값으로 대체
# 모든 결측값을 0으로 대체
df.fillna(0, inplace=True)
df = df.replace(np.NaN, 0)

# 특정 변수에 있는 결측값 'Others'로 대체
df_clean['column1'] = df['column1'].fillna('Others')

 

2.2 중복값 확인 후 제거

  • 중복값 확인 : df[df.duplicated(keep=False | 'first' | 'last')]
# 중복 여부 반환
df.duplicated(keep=False)	# 중복이면 True 반환
df.duplicated(keep='first')	# 중복값 중 첫번째 값은 False, 두번째 값부터 True 반환
df.duplicated(keep='last')	# 중복값 중 마지막 값은 False, 마지막에서 두번째 값부터 True 반환
  • 중복값 제거 : df = df.drop_duplicates(keep=False | 'first' | 'last')
df.drop_duplicates(keep=False)		# 중복값 모두 제거하고 유일한 값만 표시
df.drop_duplicates(keep='first')	# 중복값 중 처음 값만 표시 (생략 가능)
df.drop_duplicates(keep='last')		# 중복값 중 마지막 값만 표시

df = df.drop_duplicates()	# 중복값 처리 후 저장

 

2.3 데이터 자료형 변환

: 분석의 편리를 위해 열 이름은 영어로 바꿔주고 데이터 정수형으로 바꾸기

  • 날짜형 데이터(yyyy-mm-dd) 정수형 변환
# 연도, 월, 일을 정수형으로 변환하는 함수 정의
def parse_year(s):
	return int(s[:4])
def parse_month(s):
	return int(s[5:7])
def parse_day(s):
	return int(s[8:])
    
# Pandas DataFrame에서 row별로 루프를 도는 것이 느리기 떄문에 
# apply() 함수 이용하여 벡터 연산 진행
df['year'] = df['date'].apply(parse_year)
df['month'] = df['date'].apply(parse_month)
df['day'] = df['date'].apply(parse_day)
  • 변환 후 불필요한 데이터 삭제하고 열 이름 수정
# 불필요한 row 제거하고 이름 재정의
df = df.drop(columns=['date']).rename(columns={'열1':'row1', '열2':'row2'})

# 2020년의 데이터만 남기기
df = df[df['year']==2020]

 

3. 데이터 시각화

: 각 column의 변수별로 데이터 분포를 그래프로 시각화하여 특성 파악 

3.1 그래프 그리기

  • 시각화할 데이터 추출
# row1 별 데이터 개수를 내림차순 정렬한 후 열 이름을 count로 변경하여 새로운 dataframe 생성  
tmp = pd.DataFrame(df.groupby('row1').count()['row2'].sort_values(ascending=False).rename({'row2':'count'}))
  • 한글 출력을 위해 폰트 옵션 설정
import matplotlib.font_manager as fm

font_dirs = ['/usr/share/fonts/truetype/nanum', ]
font_files = fm.findSystemFonts(fontpaths=font_dirs)

for font_file in font_files:
    fm.fontManager.addfont(font_file)
    
sns.set(font="NanumBarunGothic", rc={"axes.unicode_minus":False})

 

  • 그래프 출력
# 그래프 크기 설정
plt.figrue(figsize=(20, 10))

"""
seaborn의 countplot 함수를 사용하여 그래프 출력
"""
# row1을 x축으로 하여 데이터 개수를 센 막대 그래프 출력
sns.set(style="darkgrid")
ax = sns.countplot(x="row1", data=df, palette="Set2", order=tmp.index)
plt.xticks(rotation=270)	# 긴 문자열을 모두 볼 수 있도록 270도 회전 적용
plt.show()

# row1을 x축으로 하여 7,8,9월의 데이터 개수를 센 막대 그래프 출력
sns.set(style="darkgrid")
ax = sns.countplot(x="row1", data=df[df.month.isin([7,8,9])], palette="Set2", order=tmp.index)
plt.xticks(rotation=270)
plt.show()

 

 

+ Recent posts