📊 Data Engineering

Data Preprocessing

Data Preprocessing

The process of cleaning raw data into a form suitable for analysis. Includes handling missing values, normalization, and encoding.

Detailed Explanation

Data preprocessing is the process of cleaning and transforming raw data into a form suitable for machine learning models or analysis. It is so central that 60-80% of the total time in a real data science project is spent on it. As the maxim "Garbage In, Garbage Out" says, the quality of preprocessing has a direct impact on model performance.

The main preprocessing tasks include handling missing values, detecting and removing outliers, data normalization/standardization, encoding categorical variables, and feature selection and transformation. Missing values are handled with various strategies such as deletion, mean/median imputation, KNN imputation, and multiple imputation (MICE), while outliers are detected with IQR, Z-score, Isolation Forest, and others. For scaling, you must choose an appropriate method depending on the algorithm.

Scaling methods for numerical data include Min-Max normalization (0-1 range), StandardScaler (Z-score standardization), and RobustScaler (median-based and robust to outliers). Categorical data is converted to numbers with One-Hot Encoding (nominal), Label Encoding (ordinal), Target Encoding (high-cardinality categories), and so on. Text and date data also need appropriate transformations.

Using scikit-learn's Pipeline and ColumnTransformer, you can structure the preprocessing process in a reproducible, modular form. Large datasets are processed in a distributed way with Spark or Dask, and registering preprocessing logic in a Feature Store keeps training and inference consistent. Preprocessing is not a mere chore but a core skill that reflects domain knowledge.

Code Example

scikit-learn preprocessing pipeline
# 종합적인 데이터 전처리 파이프라인 예시
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import (
    StandardScaler, MinMaxScaler, OneHotEncoder,
    OrdinalEncoder, PowerTransformer
)
from sklearn.impute import SimpleImputer, KNNImputer
from sklearn.feature_selection import SelectKBest, mutual_info_classif
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

# 1. 데이터 로드 및 탐색
df = pd.read_csv('customer_data.csv')
print(f"Shape: {df.shape}")
print(f"결측값:\n{df.isnull().sum()}")
print(f"데이터 타입:\n{df.dtypes}")

# 2. 컬럼 타입별 분류
numeric_features = ['age', 'income', 'credit_score', 'account_balance']
categorical_features = ['gender', 'region', 'membership_type']
ordinal_features = ['education']  # 순서 있는 범주

# 3. 이상치 탐지 및 처리 (IQR 방식)
def remove_outliers_iqr(df, column, threshold=1.5):
    """IQR 기반 이상치 제거"""
    Q1 = df[column].quantile(0.25)
    Q3 = df[column].quantile(0.75)
    IQR = Q3 - Q1
    lower = Q1 - threshold * IQR
    upper = Q3 + threshold * IQR
    return df[(df[column] >= lower) & (df[column] <= upper)]

# 수치형 컬럼에 이상치 처리 적용
for col in numeric_features:
    df = remove_outliers_iqr(df, col)

# 4. 전처리 파이프라인 구성
# 수치형: KNN 대체 -> Z-score 정규화 -> 정규분포화
numeric_transformer = Pipeline(steps=[
    ('imputer', KNNImputer(n_neighbors=5)),
    ('scaler', StandardScaler()),
    ('power', PowerTransformer(method='yeo-johnson'))
])

# 범주형: 최빈값 대체 -> One-Hot 인코딩
categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
])

# 순서형: 최빈값 대체 -> Ordinal 인코딩
ordinal_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OrdinalEncoder(categories=[
        ['고졸', '전문대졸', '대졸', '석사', '박사']
    ]))
])

# 5. ColumnTransformer로 통합
preprocessor = ColumnTransformer(
    transformers=[
        ('num', numeric_transformer, numeric_features),
        ('cat', categorical_transformer, categorical_features),
        ('ord', ordinal_transformer, ordinal_features)
    ],
    remainder='drop'
)

# 6. 전체 ML 파이프라인 (전처리 + 특성 선택 + 모델)
full_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('feature_selection', SelectKBest(mutual_info_classif, k=15)),
    ('classifier', RandomForestClassifier(n_estimators=100, random_state=42))
])

# 7. 학습 및 평가
X = df.drop('target', axis=1)
y = df['target']

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 전체 파이프라인 학습
full_pipeline.fit(X_train, y_train)
predictions = full_pipeline.predict(X_test)

# 8. 전처리된 데이터 확인
X_preprocessed = preprocessor.fit_transform(X_train)
feature_names = preprocessor.get_feature_names_out()
print(f"전처리 후 특성 수: {len(feature_names)}")
print(f"특성 이름: {feature_names[:10]}...")

# 9. 파이프라인 저장 (재사용)
import joblib
joblib.dump(full_pipeline, 'preprocessing_pipeline.pkl')

# 추론 시 동일한 파이프라인 사용
loaded_pipeline = joblib.load('preprocessing_pipeline.pkl')
new_predictions = loaded_pipeline.predict(new_data)

Practical Conversation

Junior: 30% of the values are missing. Is it okay to just delete those rows?
Senior: Check the missingness pattern first. The strategy differs depending on whether it's MCAR (missing completely at random) or MAR (missing at random, conditional). At 30%, KNN or MICE imputation is better than deletion. You could also try turning the missingness itself into a new feature.
Junior: Should I use normalization or standardization?
Senior: It depends on the algorithm. Use standardization for neural networks and distance-based methods (KNN, SVM), and Min-Max normalization for images or when you need a 0-1 range. Tree-based models don't require scaling, but it can help with interpretation.
Interviewer: What is data leakage and how do you prevent it?
Candidate: It's when information from the test data gets mixed into the training data. If you fit a scaler on the entire dataset during preprocessing, leakage occurs. You must fit only on the train data and only transform the test data. Using a Pipeline prevents this automatically in cross-validation as well.
Interviewer: How do you handle high-cardinality categorical variables?
Candidate: With hundreds of categories, One-Hot causes a dimensionality explosion. I use Target Encoding, Frequency Encoding, or Entity Embedding. With Target Encoding, you need to apply smoothing (regularization) to prevent overfitting.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Developer: Why shouldn't I fit StandardScaler on the entire dataset?
Senior: If the mean/variance of the test data is reflected in training, that's data leakage. In a real service you can't know the statistics of future data. If you use a Pipeline, cross_val_score automatically fits on the train portion only for each fold and only transforms the validation portion.
Developer: How should I manage preprocessing code?
Senior: The same preprocessing must be applied in training and inference. It's best to save the Pipeline with joblib or register the preprocessing logic in a Feature Store. Version control is essential too.

Cautions

  • Beware of data leakage: fit the scaler only on the train data so that test data information is not used in training.
  • When handling missing values, analyze the missingness pattern first. Deleting them unconditionally can introduce bias.
  • Do not remove outliers unconditionally. Depending on the domain, outliers can be an important signal.
  • Using a Pipeline greatly improves the reproducibility and maintainability of preprocessing logic.
  • Save the preprocessing pipeline (joblib) to keep training and inference consistent.

Learn More