# 데이터 다운로드 : 캐글 -> "finishers boston marathon 2015,2016&2017"
# 셀 너비 비율 조정하는 코드
from IPython.core.display import display, HTML
display(HTML("<style>.container { width: 70% !important; }</style>")) #width 값을 조정하면 됨
import pandas as pd
import numpy as np
marathon_2015 = pd.read_csv('marathon_results_2015.csv')
marathon_2016 = pd.read_csv('marathon_results_2016.csv')
marathon_2017 = pd.read_csv('marathon_results_2017.csv')
#정 파일위치 찾기 어려우면 새폴더 만들어서 전부 때려넣기. 이러면 경로설정 안 하고 파일명만 써도 됨
part1. 데이터 조작하기
1. 데이터 확인
2. 데이터 정제
3. 데이터(컬럼) 추가
4. 데이터 선택
5. 조건에 맞는 데이터 선택
6. 데이터 변환(시간 데이터 변환)
7. 데이터 합치기
part2. 실제 마라톤 데이터 실습
1. 데이터 확인
print(marathon_2017.shape)
marathon_2017.head(10)
marathon_2017.info()
# null값 확인하기
marathon_2017.isnull().sum()
marathon_2017.describe()
2. 데이터 정제(cleansing)
# 컬럼명 확인하기
marathon_2017.columns
len(marathon_2017.columns)
(1) 필요없는 칼럼 삭제
marathon_2017_cleaned = marathon_2017.drop(['Unnamed: 0', 'Bib', 'Unnamed: 9'], axis=1)
marathon_2017_cleaned.isnull().sum()
컬럼(=열), 메타데이터, column, feature(=속성), 독립변수+종속변수
# 참고: 필요없는 행 삭제
marathon_2017.drop([x for x in range(0, 5)], axis=0).head()
3. 데이터(칼럼) 추가
예> 조건: 60세 이상은 'senior' - T/F
marathon_2017_cleaned['senior'] = marathon_2017_cleaned.Age > 60
marathon_2017_cleaned.tail(20)
예> 'year'라는 칼럼에 2017 추가
marathon_2017_cleaned['year'] = '2017'
marathon_2017_cleaned.head()
4. 데이터 선택
# 컬럼 선택할 때
1. dot(.)을 이용
2. [] 이용 (띄어쓰기 경우)
marathon_2017_cleaned.info()
#Name 칼럼 값들을 따로 저장하기
names = marathon_2017_cleaned.Name
#이름에 띄어쓰기가 있는 경우 : ['칼럼명']을 사용
# Official Time 컬럼을 가져오기
official_time = marathon_2017_cleaned['Official Time']
5. 조건에 맞는 데이터 선택
예>> # 60세 이상인지 여부 체크하기
seniors = marathon_2017_cleaned.Age > 60
예>국적이 케냐인 사람들 데이터 가져오기
KEN_runner = marathon_2017_cleaned[marathon_2017_cleaned.Country == 'KEN']
6. 데이터 변환
marathon_2017_cleaned.info() # -> 현재 시간 데이터는 object 형식으로 들어가 있다.
방법1. 사용자 정의 함수 : 시간을 정제하는 함수 만들기
# 문자열 형태로 되어있는 시간을 int type으로 바꿔준 후 초 단위로 바꿔주는 함수
def to_second(record):
hms = record.str.split(':', n=2, expand=True) # n=2 : 2번 나눠라
second = hms[0].astype(int)*3600 + hms[1].astype(int)*60 + hms[2].astype(int)
return second
marathon_2017_cleaned['Official Time'].str.split(':', n=2, expand=True)
marathon_2017_cleaned['Official Time Sec1'] = to_second(marathon_2017_cleaned['Official Time'])
방법2. pandas 내장 함수 이용 : .to_timedelta()
# timedelta는 시스템에서 날짜시분초를 인식하는 시간 자료형
pd.to_timedelta(marathon_2017_cleaned['Official Time'])[0]
# 초 단위로 바꿔준(astype('m8[s]')) 후 int type으로 바꿔주기(astype(np.int64))
marathon_2017_cleaned['Official Time Sec2'] = pd.to_timedelta(marathon_2017_cleaned['Official Time']).astype('m8[s]').astype(np.int64)
# sort_values : 데이터 값 정렬
# Age 기준 오름차순으로 정렬
marathon_2017_cleaned.sort_values(by=['Age'], ascending=False)
#데이터 저장
marathon_2017_cleaned.to_csv('./marathon_2017.csv', index=None, header=True) #csv
marathon_2017_cleaned.to_excel('./marathon_2017.xlsx', index=None, header=True) #엑셀
7. 데이터 합치기 : concat
import pandas as pd
marathon_2015 = pd.read_csv('./marathon_results_2015.csv')
marathon_2016 = pd.read_csv('./marathon_results_2016.csv')
marathon_2017 = pd.read_csv('./marathon_results_2017.csv')
print(marathon_2015.shape)
print(marathon_2016.shape)
print(marathon_2017.shape)
marathon_2015['Year'] = '2015'
marathon_2016['Year'] = '2016'
marathon_2017['Year'] = '2017'
# index = 'Offical Time'으로 2015, 2017 데이터 합치기
marathon_2015_2017 = pd.concat([marathon_2015, marathon_2016, marathon_2017], ignore_index=True, sort=False)
# index = 'Offical Time'으로 2015, 2017 데이터 합치기
marathon_2015_2017 = pd.concat([marathon_2015, marathon_2016, marathon_2017], ignore_index=True, sort=False)
print(marathon_2015_2017.shape)
marathon_2015_2017.head()
8. 실습 : 마라톤 데이터 2015년, 2016년, 2017년 데이터 합치기
marathon_2015_2017 = marathon_2015_2017.drop(['Unnamed: 0', 'Bib', 'Citizen', 'Unnamed: 9', 'Proj Time', 'Unnamed: 8'], axis=1)
print(marathon_2015_2017.shape)
marathon_2015_2017.info()
print(marathon_2015_2017.shape)
marathon_2015_2017.head()
데이터 저장
marathon_2015_2017.to_csv('./data_boston/marathon_2015_2017.csv', index=None, header=True)
'Crawling > 데이터 시각화' 카테고리의 다른 글
데이터시각화_10가지_Scatter chart (0) | 2022.01.06 |
---|---|
데이터시각화_10가지_Line chart (0) | 2022.01.06 |
데이터시각화_10가지_Pie chart (0) | 2022.01.06 |
데이터시각화_10가지_Dual Axis, 파레토 chart (0) | 2022.01.06 |
데이터시각화_10가지_Column/Bar chart (0) | 2022.01.06 |