[Pandas] pipe / method chaining
Pandas pipe / method chaining, .pipe, method chaining, chainable pandas
정의
.pipe(func) 는 DataFrame 자체를 함수의 첫 인자로 넘겨 method chaining 을 확장. functional style Pandas.
문제: 중간 변수 남발
step1 = filter_rows(df, min_age=18)
step2 = add_column(step1, source='v2')
step3 = normalize(step2, cols=['x', 'y'])
final = summarize(step3)
가독성 나쁘고 중간 변수 이름 관리 부담.
pipe 로 chain
final = (df
.pipe(filter_rows, min_age=18)
.pipe(add_column, source='v2')
.pipe(normalize, cols=['x', 'y'])
.pipe(summarize)
)
또는 built-in method 만 사용:
result = (df
.query('age >= 18')
.assign(source='v2')
.astype({'x': 'float32'})
.groupby('country')
.agg({'value': 'sum'})
.reset_index()
)
왜 좋은가
- 불변식: 각 단계가 순수 함수
- 테스트 용이: 각 함수 단위 테스트
- 가독성: 위에서 아래로 pipeline
- 디버깅: 중간에
.pipe(print)삽입 가능
함정
- inplace=True 지양: chain 이 깨짐. 항상 새 DataFrame 반환.
- 긴 chain 은 성능 손해: 각 단계마다 새 DataFrame 생성 (메모리)
💬 댓글