0Pricing
Pandas & NumPy Academy · 강의

데이터 정제와 특성 공학

고급 정제 점검 목록을 적용하고, 날짜 특성과 비율 열을 생성하며, 단언문으로 정제된 데이터세트를 검증합니다.

데이터 정제와 특성 공학은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

감사된 데이터세트 불러오기

캡스톤 프로젝트를 계속 진행하면서 이전 단계에서 저장한 정제된 Parquet 체크포인트를 불러오십시오. 이렇게 하면 정제 단계가 데이터 수집과 분리되므로, 시간이 오래 걸리는 병합 및 구문 분석 작업을 다시 실행하지 않고도 정제 로직을 반복해서 개선할 수 있습니다. 정제된 주문 데이터를 Parquet 형식으로 읽고, 행 수와 자료형이 감사 요약의 예상값과 일치하는지 확인하십시오. Parquet 파일은 범주형 열을 포함한 모든 자료형을 보존하므로 자료형을 다시 변환할 필요가 없습니다.

import pandas as pd

# Load from checkpoint
df = pd.read_parquet('output/clean_orders.parquet')
print(f'Loaded: {df.shape}')
print(df.dtypes)
print(f'Date range: {df["order_date"].min().date()} to {df["order_date"].max().date()}')

고급 정제 체크리스트 적용

병합된 데이터세트를 불러온 후 고급 정제 체크리스트를 적용하십시오. order_id의 완전 중복 및 부분 중복을 제거하고, IQR 경계 처리를 사용하여 unit_price의 이상치를 제한하며, 일관되지 않은 category 값을 표준화하고(예: 'Electronics', 'electronics', 'ELECTRONIC'), 일반 주문에서 quantity × unit_price가 항상 양수인지 검증하십시오. 각 단계는 DataFrame을 받아 DataFrame을 반환하는 함수이므로 pipeline을 테스트할 수 있고 되돌릴 수도 있습니다.

import pandas as pd
import numpy as np

def remove_duplicates(df):
    n_before = len(df)
    df = df.drop_duplicates(subset=['order_id'], keep='first')
    print(f'Duplicates removed: {n_before - len(df)}')
    return df

def standardise_categories(df):
    df['category'] = (df['category']
                      .astype(str)
                      .str.strip()
                      .str.title())
    return df

def cap_price_outliers(df):
    q1, q3 = df['unit_price'].quantile([0.25, 0.75])
    iqr = q3 - q1
    upper = q3 + 3 * iqr
    df['unit_price'] = df['unit_price'].clip(upper=upper)
    return df

df = remove_duplicates(df)
df = standardise_categories(df)
df = cap_price_outliers(df)
print('Cleaning complete.')

날짜 특성 생성

.dt 접근자를 사용하여 주문 날짜에서 시간 특성을 추출하십시오. year, month, quarter, day_of_week, week_of_year 열을 생성하십시오. 이러한 특성은 groupby 분석(월별 매출), 시간 기반 필터(Q3만 선택), 시각화에 사용됩니다. 또한 차트 축에 사람이 읽기 쉬운 기간 레이블로 사용할 year_month 문자열 열(예: '2024-06')도 생성하십시오.

import pandas as pd

df['year'] = df['order_date'].dt.year
df['month'] = df['order_date'].dt.month
df['quarter'] = df['order_date'].dt.quarter
df['day_of_week'] = df['order_date'].dt.dayofweek  # 0=Monday
df['week'] = df['order_date'].dt.isocalendar().week.astype('int32')
df['year_month'] = df['order_date'].dt.to_period('M').astype(str)

print('Date features created:')
print(df[['order_date', 'year', 'month', 'quarter', 'year_month']].head())

항목별 매출 계산

판매 데이터세트에서 가장 기본적인 특성은 항목별 매출입니다. revenue = quantity × unit_price로 계산됩니다. 이를 새 열로 생성하십시오. 원가 데이터가 있다면 gross_margin 열도 생성하십시오. margin = (price - cost) / price로 계산합니다. 이렇게 파생된 열은 모든 매출 KPI의 구성 요소입니다. 항상 반복문 대신 벡터화된 열 연산을 사용하십시오. 전체 열에 한 번 할당하는 방식이 행마다 반복하는 것보다 훨씬 빠릅니다.

import pandas as pd

# Line-item revenue
df['revenue'] = (df['quantity'] * df['unit_price']).astype('float32')

# Gross margin (if unit_cost column exists)
if 'unit_cost' in df.columns:
    df['gross_margin'] = (df['unit_price'] - df['unit_cost']) / df['unit_price']

# Discount flag: orders with more than 20% off list price
if 'list_price' in df.columns:
    df['is_discounted'] = df['unit_price'] < df['list_price'] * 0.8

print('Revenue stats:')
print(df['revenue'].describe().round(2))

고객 코호트 할당

코호트란 공통된 특성을 공유하는 고객 그룹으로, 일반적으로 처음 구매한 시점이 같은 고객을 의미합니다. 각 고객의 첫 주문 날짜를 찾아 고객 획득 코호트를 할당하십시오. groupby('customer_id')['order_date'].min()을 사용하여 고객별 첫 주문 날짜를 계산한 다음, 이를 연-월 기간으로 변환하여 cohort_month 열을 생성하십시오. 이 코호트 레이블은 다음 단원에서 다룰 유지율 행렬의 기반입니다.

import pandas as pd

# First purchase date per customer
first_purchase = (
    df.groupby('customer_id')['order_date']
    .min()
    .dt.to_period('M')
    .astype(str)
    .rename('cohort_month')
)

# Merge back onto orders
df = df.merge(first_purchase, on='customer_id', how='left')
print('Cohort distribution (top 5):')
print(df['cohort_month'].value_counts().head())
print(f'Distinct cohorts: {df["cohort_month"].nunique()}')

고객 생애 가치 특성

고객 수준 요약 특성을 계산하십시오. 총 주문 수, 총 매출, 평균 주문 금액, 첫 구매일 및 마지막 구매일 이후 경과 일수, 구매한 고유 범주 수가 포함됩니다. 이러한 값을 고객 수준의 보강 열로 기본 DataFrame에 다시 병합하십시오. 이 특성은 고객 세분화(예: 고가치 고객과 저가치 고객)에 사용되며, 이탈 또는 추가 판매 가능성을 예측하는 기계 학습 모델의 입력으로도 사용됩니다.

import pandas as pd

customer_stats = df.groupby('customer_id').agg(
    total_orders=('order_id', 'nunique'),
    total_revenue=('revenue', 'sum'),
    avg_order_value=('revenue', 'mean'),
    categories_purchased=('category', 'nunique'),
    first_order=('order_date', 'min'),
    last_order=('order_date', 'max')
).reset_index()

customer_stats['days_as_customer'] = (
    (customer_stats['last_order'] - customer_stats['first_order'])
    .dt.days
)

print(customer_stats.describe().round(2))

어설션을 사용한 스키마 검증

특성을 생성한 후 스키마 검증 어설션을 실행하여 분석 단계로 전달하기 전에 데이터가 예상 조건을 충족하는지 확인하십시오. 예상되는 모든 열이 존재하는지, 일반 주문의 매출이 음수가 아닌지, cohort_month가 null이 아닌지, year_month가 분석 연도와 일치하는지 확인하십시오. 이러한 어설션은 계약처럼 작동합니다. 하나라도 실패하면 잘못된 결과를 조용히 생성하는 대신 명확한 오류 메시지와 함께 pipeline이 즉시 중지됩니다.

import pandas as pd

def validate_clean_df(df):
    required_cols = ['order_id', 'customer_id', 'revenue', 'year_month',
                     'cohort_month', 'category', 'region', 'order_date']
    missing = [c for c in required_cols if c not in df.columns]
    assert not missing, f'Missing columns: {missing}'

    assert (df['revenue'] >= 0).all(), 'Negative revenue found'
    assert df['cohort_month'].notna().all(), 'Null cohort_month values'
    assert df['order_date'].notna().all(), 'Null order dates'
    print(f'Validation passed: {len(df):,} rows, {len(df.columns)} columns')

validate_clean_df(df)

빈도가 낮은 범주 처리

실제 데이터세트에서는 일부 범주나 지역이 몇 번만 나타나 의미 있는 분석을 하기 어려운 경우가 있습니다. 수십 개의 단일 주문 범주로 차트가 복잡해지지 않도록 빈도가 낮은 값을 'Other'로 바꾸십시오. 실용적인 기준은 행의 0.5% 미만에서 나타나는 값을 하나로 묶는 것입니다. 이는 기계 학습에서도 중요합니다. 희귀한 범주 200개를 원-핫 인코딩하면 메모리를 낭비하고 잡음이 늘어나기 때문입니다.

import pandas as pd

def collapse_rare_values(df, col, min_pct=0.005):
    threshold = len(df) * min_pct
    counts = df[col].value_counts()
    rare = counts[counts < threshold].index
    n_rare = len(rare)
    df[col] = df[col].apply(lambda x: 'Other' if x in rare else x)
    print(f'{col}: collapsed {n_rare} rare values into "Other"')
    return df

df = collapse_rare_values(df, 'category', min_pct=0.005)
df = collapse_rare_values(df, 'region', min_pct=0.005)
print('Category distribution after collapsing:')
print(df['category'].value_counts())

특성 생성 데이터세트 저장

완전히 정제되고 특성이 생성된 DataFrame을 Parquet 체크포인트로 저장하십시오. 이것이 바로 분석 준비 데이터세트이며, 데이터 수집, 정제, 특성 생성의 모든 단계가 끝난 결과입니다. 이후의 pipeline 단계(KPI 계산, 시각화, 보고)는 이 체크포인트에서 데이터를 읽습니다. 이 체크포인트는 결과물의 역할도 합니다. 팀원과 공유하거나 데이터 레이크에 업로드하여 다른 사람이 SQL 또는 Pandas로 조회하도록 할 수 있습니다.

import pandas as pd

# Convert category columns back to Categorical for memory efficiency
for col in ['category', 'region', 'acquisition_channel']:
    if col in df.columns:
        df[col] = df[col].astype('category')

# Save analysis-ready dataset
df.to_parquet('output/analysis_ready.parquet', index=False)

# Also save customer stats for segmentation
customer_stats.to_parquet('output/customer_stats.parquet', index=False)

print(f'Analysis-ready dataset: {df.shape}')
print(f'Memory usage: {df.memory_usage(deep=True).sum()/1e6:.1f} MB')

특성 생성 요약

좋은 특성 생성은 예측에 유용한 신호를 추가하면서도 pipeline을 이해하고 테스트할 수 있도록 균형을 맞춥니다. 이 단계에서 생성한 특성(매출, 날짜 구성 요소, cohort_month, 고객 통계, 통합된 범주)은 모두 프로젝트 설정에서 정의한 분석 목표에 따라 결정되었습니다. 근거 없이 수십 개의 특성을 만들고 싶은 유혹을 참으십시오. 각 특성에 대해 최소 하나의 KPI나 시각화에서 이 특성을 사용할 것인가?라고 질문하십시오. 그렇지 않다면 나중으로 미루십시오. 분석 준비 데이터세트는 간결하고 목적에 맞게 유지하십시오.

import pandas as pd

# Summary of engineered features
df = pd.read_parquet('output/analysis_ready.parquet')

original_cols = ['order_id', 'customer_id', 'order_date', 'quantity', 'unit_price']
engineered_cols = [c for c in df.columns if c not in original_cols]

print('Original columns:', original_cols)
print('Engineered features:', engineered_cols)
print(f'Total columns: {len(df.columns)}')
print(f'Total rows: {len(df):,}')

코드에 결정 사항 문서화

명확하지 않은 모든 정제 또는 특성 생성 결정에 이유를 설명하는 주석을 추가하십시오. 나중의 본인이나 팀원은 IQR 배수를 1.5가 아닌 3으로 설정한 이유나 희귀 범주 기준으로 0.5%를 사용한 이유를 기억하지 못할 수 있습니다. 인라인 주석과 결정 사항 기록(프로젝트 README 또는 마크다운 파일에 작성한 간단한 목록)은 pipeline을 유지 관리하고 감사할 수 있게 합니다. 깔끔하게 문서화된 코드가 진정한 결과물이며, 출력 파일은 그 결과일 뿐입니다.

# Engineering decisions log
DECISIONS = '''
# Data Cleaning & Feature Engineering Decisions

## Duplicate handling
Kept first occurrence of duplicate order_id (most likely the original order).

## Outlier capping
Unit price capped at Q3 + 3*IQR (not 1.5*IQR) because price distribution
has legitimate high-value enterprise orders that should not be removed.

## Rare category threshold: 0.5%
Values below 0.5% of total orders collapsed to "Other" to keep charts readable
and avoid spurious significance in category-level tests.

## Cohort assignment
Cohort = first purchase calendar month (not signup month), because many users
sign up but do not purchase until months later.
'''
print(DECISIONS)

빠른 확인

이 단원에서 배운 데이터 분석 개념을 이해했는지 확인해 보십시오.

단원 요약

이 단원에서는 다음을 배웠습니다. 모듈식 정제 함수(중복 제거, 이상치 제한, 범주 표준화)는 각각 DataFrame을 받아 반환하므로 쉽게 테스트할 수 있고, 특성 생성을 통해 날짜 구성 요소, 항목별 매출, 고객 코호트, 요약 통계를 만들었으며, 스키마 검증 어설션은 정제 단계에서 분석 단계로 넘어가는 과정을 보호합니다. 다음 단계에서는 프로젝트의 핵심 KPI인 월별 코호트 유지율, 제품 매출, 이동 활성 사용자를 계산합니다.

자주 묻는 질문

“데이터 정제와 특성 공학” 강의는 무료인가요?

네 — “데이터 정제와 특성 공학” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“데이터 정제와 특성 공학”에서 뭘 배우나요?

고급 정제 점검 목록을 적용하고, 날짜 특성과 비율 열을 생성하며, 단언문으로 정제된 데이터세트를 검증합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“데이터 정제와 특성 공학” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 프로젝트 설정과 데이터 수집
  2. 데이터 정제와 특성 공학
  3. 분석과 KPI 계산
  4. 최종 시각화와 보고서 내보내기
← Pandas & NumPy Academy(으)로 돌아가기