DataFrame의 값에 함수를 적용할 때 사용하는 apply 함수와 applymap 함수에 대해 알아보자.
apply 함수
DataFrame에 걸쳐 Series 단위에 (또는 row 단위에) 함수를 적용하고 싶을 때 사용한다.
데이터프레임.apply(함수, axis = 기준 축)
raw_data = {"A":[-1,4,13], "B":[2,5,6], "C":[0,6,11]}
df = pd.DataFrame(raw_data, index = ['first', 'second', 'third'])
print(df)
# 출력:
# A B C
# first -1 2 0
# second 4 5 6
# third 13 6 11
f = lambda x : x.max() - x.min()
print(df.apply(f)) # apply 함수의 기본 축은 행 방향이기 때문에, 각 column에 함수가 적용된다.
# 출력:
# A 14
# B 4
# C 11
# dtype: int64
위 코드에서 f 함수의 인자로 DataFrame의 각 column이 들어가게 된다.
applymap 함수
DataFrame에 걸쳐 element 단위로 함수를 적용하고 싶을 때 사용한다.
raw_data = {"A":[-1,4,13], "B":[2,5,6], "C":[0,6,11]}
df = pd.DataFrame(raw_data, index = ['first', 'second', 'third'])
print(df)
# 출력:
# A B C
# first -1 2 0
# second 4 5 6
# third 13 6 11
f = lambda x : -x
print(df.apply(f))
# 출력:
# A B C
# first 1 -2 0
# second -4 -5 -6
# third -13 -6 -11
위 코드에서 f 함수의 인자로 DataFrame의 element가 들어가게 된다.
'AI > Pandas' 카테고리의 다른 글
[Pandas] column 별로 데이터의 비율 알아내는 방법 (0) | 2023.03.09 |
---|---|
[Pandas] DataFrame 출력할 때 보여지는 데이터 개수 늘리는 방법 (0) | 2023.03.09 |
[Pandas] map 함수 VS replace 함수 (0) | 2023.03.09 |
[Pandas] DataFrame과 Series 간의 연산 (0) | 2023.03.09 |
[Pandas] DataFrame (0) | 2023.03.09 |