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

Prose 처럼 읽히는 파이프라인

한 statement 씩 쓴 Pandas 코드는 중간 변수의 덤불로 자라기 쉬워 — df1, df2, df_filtered, df_filtered_grouped. Modern 스타일은 method chaining: 모든 단계가 새 DataFrame 반환, 들여쓰기, 파이프라인이 위에서 아래로 연산 sequence 처럼 읽혀.

가능하게 하는 두 메서드는 assign() (입력 mutate 없이 column 추가/덮기) 와 pipe() (체인 안에 임의 함수 apply). query(), groupby(), sort_values() 와 결합하면 대부분의 분석 파이프라인을 한 들여쓰기된 expression 으로 표현할 수 있어.

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

비-trivial Pandas 스크립트 하나 골라서 단일 chained expression 으로 다시 써. 입력과 최종 출력만 명명. 못 한다면 (예: 두 분기가 중간점 공유) 그 중간점이 이름 받아 마땅한 변수. Chain 이 본인이 작성 전에 파이프라인을 설계하게 강제하는 거 느껴봐.

Progress

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

댓글 0

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

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