외국 데이터를 가져오는 경우, 국내에서 잘 사용하지 않는 도량형 단위가 많다.
ex) 마일, 야드, 온스 등등
이를 미터,평 그램으로 변환하는 것이 좋다.
import pandas as pd
df = pd.read_csv(r'C:\Users\kjt63\OneDrive\바탕 화면\python\data_analysis\sample\part5\auto-mpg.csv',header=None)
# 열 이름 지정
print(df)
df.columns= [ 'mpg','cylinders','displacement','horsepower','weight','acceleration','model year','origin','name']
print(df.head(3))
print('\n')
# mpg(mile per gallon)를 kpl(killometer per liter)로 변환 (mpg_to_kpl = 0.425 )
mpg_to_kpl = 1.60934/3.78541
df['kpl']= df['mpg'] * mpg_to_kpl
print(df.head(3))
# kpl 열을 소수점 아래 둘째자리까지 반올림
df['kpl']= df['kpl'].round(2)
print(df.head(3))
import pandas as pd
import numpy as np
df = pd.read_csv(r'C:\Users\kjt63\OneDrive\바탕 화면\python\data_analysis\sample\part5\auto-mpg.csv',header=None)
# 열 이름 지정
print(df)
df.columns= [ 'mpg','cylinders','displacement','horsepower','weight','acceleration','model year','origin','name']
print(df.info())
print(df.dtypes)
# 확인해본 결과 'horsepower'열이 문자열로 저장되어있다.
print(df['horsepower'].unique())
df['horsepower'].replace('?',np.nan,inplace=True)
df.dropna(subset=['horsepower'],how='any',axis=0,inplace=True)
# 문자열을 실수형으로 변환 .astype('float')
df['horsepower'] = df['horsepower'].astype('float')
print(df['horsepower'].dtypes)
print(df['origin'].unique())
# 숫자를 문자열 자료형으로 자동변환한다.
df['origin'].replace({1:'USA',2:'EU',3:'JPN'},inplace=True)
print(df['origin'].unique())
print(df['origin'].dtypes)
# 앞에서 origin 열의 국가이름은 문자열 데이터로 변경되었따.
# 값을 확인해보면 3개의 국가이름이 계속 반복된다. 이처럼 유한개의 고유값이 반복적으로 나타나는 경우에는
# 범주형(category) 데이터로 표현하는 것이 효율적이다.
# astype('category') 메소드를 이용하여 범주형데이터로 변경한다.
df['origin']= df['origin'].astype('category')
print(df['origin'].dtypes)
# 범주형데이터형을 문자열로 다시 변환하려면 astype('str') 메소드 이용
df['origin'] = df['origin'].astype('str')
print(df['origin'].dtypes)
# 마지막으로 model year열의 자료형을 살펴보면 int64 정수형으로 남겨둬도 무방하지만,
# 연도의 시간적 순서는 의미가있으나 숫자의 상대적 크기는 별 의미가없으므로 범주형데이터로 변환하는것이 적절하다.
print(df['model year'].sample(3))
df['model year'] = df['model year'].astype('category')
print(df['model year'].sample())