본문 바로가기
C.W.K.
Stream
Lesson 07 of 07 · published

Method Chaining 과 assign() — 읽기 좋은 transform

~11 min · pandas, style, method-chaining

Level 0구경꾼
0 XP0/47 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

글처럼 읽히는 파이프라인

한 문장씩 쌓아 올린 Pandas 코드는 중간 변수 덤불로 자라기 쉬워 — df1, df2, df_filtered, df_filtered_grouped. Modern 스타일은 method chaining 이야. 모든 단계가 새 DataFrame 을 반환하고, 들여쓰기로 이어지고, 파이프라인이 위에서 아래로 연산 순서 그대로 읽혀.

이걸 받쳐 주는 메서드가 둘이야: assign() (입력을 건드리지 않고 column 을 추가하거나 덮어쓰기) 그리고 pipe() (체인 중간에 아무 함수나 끼워 넣기). query(), groupby(), sort_values() 와 엮으면 웬만한 분석 파이프라인이 들여쓰기 한 덩어리 안에 다 들어가.

Code

스파게티에서 체인으로 — 같은 로직, 가독성 천지차·python
import pandas as pd

# --- 스파게티 스타일 (저항해) ---
raw = pd.read_csv('orders.csv')
raw['order_date'] = pd.to_datetime(raw['order_date'])
filtered = raw[raw['status'] == 'completed']
filtered = filtered[filtered['amount_usd'] > 0]
filtered['month'] = filtered['order_date'].dt.to_period('M')
monthly = filtered.groupby('month', as_index=False).agg(
    revenue=('amount_usd', 'sum'),
    orders=('order_id', 'nunique'),
)
monthly = monthly.sort_values('month')

# --- 체인 스타일 (이렇게) ---
monthly = (
    pd.read_csv('orders.csv')
      .assign(order_date=lambda d: pd.to_datetime(d['order_date']))
      .query("status == 'completed' and amount_usd > 0")
      .assign(month=lambda d: d['order_date'].dt.to_period('M'))
      .groupby('month', as_index=False)
      .agg(revenue=('amount_usd', 'sum'),
           orders=('order_id', 'nunique'))
      .sort_values('month')
)
<code>pipe()</code> 로 본인 함수 체인에 끼워넣기·python
def attach_country(df: pd.DataFrame, customers: pd.DataFrame) -> pd.DataFrame:
    return df.merge(customers[['customer_id', 'country']],
                    on='customer_id', how='left', validate='many_to_one')

result = (
    orders
      .pipe(attach_country, customers=customers)
      .query("country == 'KR'")
      .groupby('order_date', as_index=False)['amount_usd'].sum()
)

External links

Exercise

만만치 않은 Pandas 스크립트 하나 골라서 하나의 chained expression 으로 다시 써 봐. 이름은 입력과 최종 출력에만 붙여. 안 되는 부분이 있다면 (예: 두 갈래가 중간 결과 하나를 공유) 그 중간 결과가 진짜로 이름 붙일 자격이 있는 변수야. Chain 이 코드를 쓰기 전에 파이프라인부터 설계하게 만드는 걸 느껴 봐.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.