[python] 외부데이터

2021. 4. 29. 02:48Python/문법

Ver. Jupyter Notebook (Anaconda3)

▶ 데이터 읽기

>>> import pandas as pd
>>> import numpy as np

>>> marathon_2015 = pd.read_csv('./date_boston/marathon_results_2015.csv')
>>> marathon_2016 = pd.read_csv('./date_boston/marathon_results_2016.csv')
>>> marathon_2017 = pd.read_csv('./date_boston/marathon_results_2017.csv')

 

▶ 데이터 확인

>>> print(marathon_2015.shape)
>>> marathon_2015.head()


>>> marathon_2017.info()

# null값 확인하기
>>> marathon_2017.isnull().sum()

# 통계값 확인
>>> marathon_2017.describe()

 

▶ 데이터 정제(cleansing)

# columns명 확인하기
>>> print(len(marathon_2017.columns))
>>> list(marathon_2017.columns)



# 필요없는 columns 삭제
# axis=0: index, axis=1: columns

>>> marathon_2017_cleaned = marathon_2017.drop(['Unnamed: 0', 'Bib', 'Unnamed: 9'], axis=1)
>>> print(len(marathon_2017_cleaned.columns))
>>> marathon_2017_cleaned.isnull().sum()

 

▶ 데이터 추가(columns)

# 조건: 60세 이상은'senior' - T/F
# 특정 컬럼 선택할 때: 데이터.컬럼명

# marathon_2017_cleaned.Age
# marathon_2017_cleaned['Age']
# 둘다 같은 의미지만 컬럼명이 띄워진것은 ['컬럼명']으로 사용해야 함.
# ex) marathon_2017_cleaned['Official Time']

60세 이상은 senior 컬럼을 만들어서 True / 이하는 False로 입력
>>> marathon_2017_cleaned['senior'] = marathon_2017_cleaned.Age > 60
>>> marathon_2017_cleaned.tail(20)

# 'year' columns에 2017 value 추가 
>>> marathon_2017_cleaned['year'] = '2017'
>>> marathon_2017_cleaned.head()

 

▶ 데이터 선택

# 조건: 60세 이상은'senior' - T/F
# 특정 컬럼 선택할 때: 데이터.컬럼명

# marathon_2017_cleaned.Age
# marathon_2017_cleaned['Age']
# 둘다 같은 의미지만 컬럼명이 띄워진것은 ['컬럼명']으로 사용해야 함.
# ex) marathon_2017_cleaned['Official Time']

60세 이상은 senior 컬럼을 만들어서 True / 이하는 False로 입력
>>> marathon_2017_cleaned['senior'] = marathon_2017_cleaned.Age > 60
>>> marathon_2017_cleaned.tail(20)

# 'year' columns에 2017 value 추가 
>>> marathon_2017_cleaned['year'] = '2017'
>>> marathon_2017_cleaned.head()

 

▶ 조건에 맞는 데이터 선택

# 60세 이상인지 체크하기
>>> seniors = marathon_2017_cleaned.Age > 60
>>> seniors
# 국적이 케냐인 사람들 데이터 가져오기
>>> KEN_runner = marathon_2017_cleaned[marathon_2017_cleaned.Country == 'KEN']
>>> print(KEN_runner.shape)
>>> KEN_runner   # 8명이 참가해서 상위 등수들(overall) 차지 (1등, 5등, 15등, 18등, 21등, 44등, 54등, 70등)

 

▶ 데이터 변환

# 시간 데이터가 object 형태이고, 이를 시간 형태로 바꾸고 초 단위로 바꾸기
# 방법1. 사용자 정의 함수 : 시간을 정제하는 함수 만들기
>>> def to_second(record):
           hms = record.str.split(':', n=2, expand=True)   #n=2, expand=True : 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.head()

>>> marathon_2017_cleaned['Official Time Sec1'] = to_second(marathon_2017_cleaned['Official Time'])
>>> marathon_2017_cleaned.head()

# 방법2. pandas 내장 함수 이용 : .to_timedelta()
>>> pd.to_timedelta(marathon_2017_cleaned['Official Time'])

# 초 단위로 바꿔준(astype('m8[s]')) 후 int type으로 바꿔주기(astype(np.int64))
# 'm8[s] >>> s:초 / m:분 / h시간'
>>> marathon_2017_cleaned['Official Time Sec2'] = pd.to_timedelta(marathon_2017_cleaned['Official Time']).astype('m8[s]').astype(np.int64)
>>> marathon_2017_cleaned.head()

 

▶ 데이터 저장

# csv : 빠름, 용량 적음, 한글 꺠질 우려가 있음.
# xlsx : 느림, 한글은 xlsx가 좋음

# csv로 저장
>>> marathon_2017_cleaned.to_csv('./data_boston/marathon_2017.csv', index=None, header=True)

# xlsx로 저장
>>> marathon_2017_cleaned.to_excel('./data_boston/marathon_2017.xlsx', index=None, header=True)

'Python > 문법' 카테고리의 다른 글

[Python] 데이터 시각화  (0) 2021.04.29
[python] kaggle, boston marathon  (0) 2021.04.29
[Python] 정리  (0) 2021.04.29
[python] pandas  (0) 2021.04.28
[python] 심화  (0) 2021.04.27