데이터 전처리 (병합)
인덱스를 정렬하기 위해서는?
pd.concat([데이터프레임 1, 2, 3]).reset_index(drop=True)
▶ 0부터 차례대로 인덱스 정렬됨
concat의 axis 기본값은 0 = 위아래로 정렬.
pd.concat([데이터프레임 1, 2, 3] 'axis=0')
▶ 양옆으로 정렬해주기 위해서는 axis를 1로 설정해야 함.
pd.merge(데이터 프레임1,2, on='컬럼', how='inner')
how로 정렬 기준을 정할 수 있음. 디폴트 값은 inner. outer,left,right 등으로 설정 가능.
데이터 전처리 (집계)
groupby
EX) pd.groupby('컬럼').'집계인덱스'()
▶ 컬럼이 인덱스가 되고 그룹별 집계 인덱스가 출력됨.
유의할 점! : 문자열 같이 집계를 하기 힘든 컬럼을 넣을 경우 오류가 뜸.
pivot table
EX) pivot = df.pivot_table(index='A', columns='B', values='C', aggfunc='D')
▶ A가 행, B가 열로 C를 집계함. 이때 집계함수는 D에 삽입
데이터 전처리 (정렬)
2회차 세션 내용
describe() 메서드 = 데이터 분포 형태를 파악할 수 있음.
▶ 카운트, 평균, 최대, 최소 등의 데이터를 보여줌.
describe(include='all') = 범주형 변수 포함 전체 분석 메서드
count : 결측치가 아닌 데이터의 개수
unique : 고유값의 개수 (카테고리 수)
top : 가장 빈번한 값 (최빈값)
freq : 최빈값의 빈도
범주형 데이터 분석 - value_counts()
EX)
sex_counts = titanic['Sex'].value_counts() ▶ 성별 분포 (개수로 출력)
sex_ratios = titanic['Sex'].value_counts(normalize=True) ▶ 성별 분포 (비율로 출력)
결측치란?
컬럼별 결측치를 확인하는 법
missing_counts = titanic.isnull().sum()
print(missing_counts)
▶ 데이터 프레임의 널 값의 개수를 카운팅.
결측치 비율을 확인하는 법
missingratios = (titanic.isnull().sum() / len(titanic) * 100).round(2)
missing_summary = pd.DataFrame({
'결측치개수': missingcounts,
'결측치비율(%)': missing_ratios})
결측치가 있는 행 삭제
titanic_dropped_all = titanic.dropna()
print(f"모든 결측치 행 삭제 후: {titanic_dropped_all.shape}")
print(f"삭제된 행: {len(titanic) - len(titanic_dropped_all)}개")
print(f"데이터 손실률: {(1 - len(titanic_dropped_all)/len(titanic))*100:.1f}%")
행은 언제 삭제?
결측치가 있는 컬럼 삭제
titanic_dropped_cols = titanic.dropna(axis=1)
print(f"결측치 컬럼 삭제 후: {titanic_dropped_cols.shape}")
print(f"삭제된 컬럼: {set(titanic.columns) - set(titanic_dropped_cols.columns)}")
컬럼은 언제 삭제?
subset 옵션 활용으로 최소한의 결측치만 제거
titanic_age_dropped = titanic.dropna(subset=['Age'])
print(f"\nAge 결측치만 삭제 후: {titanic_age_dropped.shape}")
print(f"Age 결측치로 삭제된 행: {len(titanic) - len(titanic_age_dropped)}개")
결측치를 대체하는 법?
결측치 대체할 수 있는 값 : 상황
1. 평균값 : 정규분포에 가까운 연속형 변수
2. 중위수 : 이상치가 많거나 치우친 분포
3. 최빈값 : 범주형 변수
4. 특정값 : 비즈니스 로직상 의미가 있는 값
5. 예측값 : 다른 변수들로 예측한 값
평균값으로 대체하기 (예시)
age_mean = titanic_filled['Age'].mean()
titanic_filled['Age_mean_filled'] = titanic_filled['Age'].fillna(age_mean)
print(f"\n평균값({age_mean:.1f}세)으로 대체 완료")
print(f"대체 후 결측치: {titanic_filled['Age_mean_filled'].isnull().sum()}개")
▶ 중위값으로 대체하고 싶을 때는 mean 함수를 median 함수로 변경만 하면 됨.
타이타닉 필드에서 age 조건에 따라 추출하기
1. Nan인 사람 조회
titanic_filled[titanic_filled['Age'].isna()]
▶ 데이터 프레임에서 조건을 부여하는 거기때문에 [] 안에 조건 생성
2. 13세 이상인 사람 조회
titanic_filled[titanic_filled['Age']>=13]