페이지 3: 데이터 클리닝 및 전처리

3. 데이터 클리닝 및 전처리

실제 데이터는 종종 지저분합니다. 데이터 클리닝은 분석의 품질과 정확성을 보장하는 중요한 단계입니다.

3.1. 결측값 처리

결측값(NaN)은 흔합니다. pandas는 이를 식별하고 채우거나 제거하는 메서드를 제공합니다.

# 결측값 확인
print(df.isna().sum())

# 'Age' 열의 결측값을 평균으로 채우기
df['Age'].fillna(df['Age'].mean(), inplace=True) 

# 'City' 열에 결측값이 있는 행 삭제
df.dropna(subset=['City'], inplace=True)
print(df.isna().sum())

3.2. 데이터 유형 변경

분석에 적합한 데이터 유형을 가지도록 열을 확인합니다.

# 'Age'를 정수형으로 변환
df['Age'] = df['Age'].astype(int) 

# 'Date' 열을 datetime 객체로 변환
df['Date'] = pd.to_datetime(df['Date'])
print(df.info())

3.3. 중복 제거

중복된 행은 분석을 왜곡할 수 있습니다. .drop_duplicates()를 사용하여 제거하세요.

# 모든 열을 기반으로 중복 행 제거
df.drop_duplicates(inplace=True)

# 특정 열을 기반으로 중복 제거
df.drop_duplicates(subset=['Name', 'Age'], inplace=True)
print(df.shape)

3.4. 열 이름 변경

명확성과 일관성을 위해 열 이름을 변경합니다.

df.rename(columns={'old_name': 'new_name', 'Another Old': 'Another New'}, inplace=True)
print(df.columns)