본문 바로가기

Python

reduce 함수

1. reduce 함수

lamda, zip, reduce, enumerate 등 기본적인 함수는 초반에 파이썬을 공부할 때 보기는 하는데

어떻게 어떤 식으로 효율적으로 사용할 것인지는 여전히 잘 모른다.(코드가 지저분)

그래도 구체적인 목적으로 필요한 분석을 진행하면서

하나씩 뜯어보는 습관 덕분에 함수에 대한 이해와 활용도가 조금은 나아지는 듯. 

reduce 함수도 참 많이 봤는데 와닿지가 않다가 최근에 다시 정리를 해보는데.

https://codepractice.tistory.com/86

 

(파이썬) functools 모듈의 reduce 함수

functools 모듈의 reduce 함수는 다음과 같다. def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: value = next(it) else: value = initializer for element in i..

codepractice.tistory.com

reduce 함수 동작 원리를 설명해주면서 내 입맛에는 가장 잘 맞는 설명이 되어있는 사이트.

 

 

2. reduce 함수의  구체적 활용

데이터 프레임 3개 병합을 어떻게 하지?

https://stackoverflow.com/questions/23668427/pandas-three-way-joining-multiple-dataframes-on-columns

 

pandas three-way joining multiple dataframes on columns

I have 3 CSV files. Each has the first column as the (string) names of people, while all the other columns in each dataframe are attributes of that person. How can I "join" together all three CSV

stackoverflow.com

1
2
3
4
5
dfs = [df0, df1, df2, dfN]
 
df_final = reduce(lambda left,right: pd.merge(left,right,on='name'), dfs)
 
 
cs

위 reduce 함수 설명에 따르자면 function에는  2개 데이터 프레임을 매개변수로 받아서 merge 하는 함수 lambda

iterable 에는 데이트 프레임 리스트가 전달.