[Pandas] DataFrame apply

김유상·2023년 1월 17일
0

pandas dataframe의 apply function에 대해서 알아보았다.

apply는 파라미터로 오는 function을 이용해 dataframe에 대해 처리해주는 역할을 한다. 아래와 같은 상황에서는 마치 np.sqrt(df)와 같은 의미로 사용된다.

df.apply(np.sqrt)

lambda의 경우에도 똑같이 사용될 수 있다.

df[pm_i] = df[pm_i].apply(lambda x : 'very bad' if x >=76 else 'bad' if x>=36 else 'not bad' if x>=16 else 'good')

lambda에 x를 df[pm_i]로 사용한 것과 같은 의미로 해석할 수 있다.

그러나 대체될 수 있는 기능을 굳이 apply를 이용해 사용하는 이유는 apply는 axis, index, result_type 매개변수를 입력해줌으로써 dataframe을 편리하게 변경할 수 있기 때문이다.

아래의 예시는 참조에서 가져온 예시이다.

>>> df.apply(lambda x: [1, 2], axis=1, index=['foo', 'bar']), result_type='expand')
   foo  bar
0    1    2
1    1    2
2    1    2

Referenced: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html

profile
continuous programming

0개의 댓글