- 라이브러리 및 데이터 불러오기
- 탐색적 데이터 분석(EDA)
문제에서 주어지는 데이터를 불러오고 EDA 하는 방법에 대한 흐름과 문법들을 잘 기억해놓자!
데이터 : 성인 인구조사 소득 예측
.
주어진 3개의 데이터 파일
- X_train.csv
- X_test.csv
- y_train.csv
# 판다스 라이브러리 import pandas as pd
# 데이터 불러오기 X_train = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/edadata/data_atype/X_train.csv") y_train = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/edadata/data_atype/y_train.csv") X_test = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/edadata/data_atype/X_test.csv")
# 데이터 샘플(상위 5개) X_train.head()
# 데이터 샘플(하위 5개) X_train.tail()
# 데이터 샘플(랜덤) X_train.sample(3)
.shape
(괄호 없음 주의!)# 데이터 크기 X_train.shape
.info()
# 타입 X_train.info()
.describe()
# 수치형 컬럼 통계값 확인(train) X_train.describe()
# 수치형 컬럼 통계값 확인(test) X_test.describe()
.describe(include = 'O')
(대문자 O 주의!)# 범주형 컬럼 통계값 확인 (train) X_train.describe(include='O')
include = 'object'
로도 사용 가능
# 범주형 컬럼 통계값 확인 (test) X_test.describe(include='object')
.isnull()
: 모든 데이터 중 결측치에 대해 True, False로 반환
.isnull().sum()
: 칼럼별 결측치의 갯수를 보고 싶을 때 사용
# 결측치 (train)
# X_train.isnull()
X_train.isnull().sum()
# y_train 샘플 확인 y_train.head()
-.value_counts()
(count's' 주의!)
# target(label)별 개수 확인 y_train['income'].value_counts()
.corr()
# 상관관계 X_train.corr(numeric_only=True)
# 최신 판다스에서 오류 발생 시 numeric_only=True 사용 # sum(), mean() 등 포함
# 데이터 불러오기 train = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/edadata/data_btype/train.csv") test = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/edadata/data_btype/test.csv")
# 데이터 크기 train.shape, test.shape
# 데이터 샘플 train.head()
# 예측 해야할 값 train['income'].value_counts()
# 조건 con0 = train['income'] == "<=50K" #0 : 하위 소득 con1 = train['income'] == ">50K" #1 : 상위 소득 conf = train['sex'] == "Female" # 여성 conm = train['sex'] == "Male" #남성
# 남성과 여성의 수 len(train[conm]), len(train[conf])
# 남성 중 0과 1 (인원 수) len(train[con0 & conm]), len(train[con1 & conm])
# 남성 중 0과 1 (비율) len(train[con0 & conm]) / len(train[conm]), len(train[con1 & conm]) / len(train[conm])
# 여성 중 0과 1 (인원 수) len(train[con0 & conf]), len(train[con1 & conf])
# 여성 중 0과 1 (비율) len(train[con0 & conf]) / len(train[conf]), len(train[con1 & conf]) / len(train[conf])
.concat()
axis = 0 은 위아래로 합치고, 1은 좌우로 합친다.# X_train y_train 합치는 것 예시 df = pd.concat([X_train, y_train['income']], axis = 1) df.shape
.iloc()
또는 .loc()
활용하기.copy()
로 복사본 생성 (원본 데이터에 영향을 주지 않기 위해)# train 분리 예시 X_tr = train.iloc[:,:-1].copy() y_tr = train.iloc[:,[0,-1]].copy() X_tr.shape, y_tr.shape