Pandas apply()를 제자리에서 사용하는 방법
pandas apply() 함수는 pandas DataFrame의 행이나 열에 함수를 적용하는 데 사용할 수 있습니다.
이 함수는 inplace 인수를 제공하는 drop() 및 replacement() 와 같은 다른 함수와 다릅니다.
df. drop ([' column1 '], inplace= True ) df. rename ({' old_column ': ' new_column '}, inplace= True )
apply() 함수에는 내부 인수가 없으므로 내부 DataFrame을 변환하려면 다음 구문을 사용해야 합니다.
df = df. apply ( lambda x: x* 2 )
다음 예는 다음 pandas DataFrame에서 실제로 이 구문을 사용하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
예 1: 열에 apply() 사용
다음 코드는 apply()를 사용하여 데이터 프레임 열을 제자리에서 변환하는 방법을 보여줍니다.
#multiply all values in 'points' column by 2 in place df. loc [:, ' points '] = df. points . apply ( lambda x: x* 2 ) #view updated DataFrame df points assists rebounds 0 50 5 11 1 24 7 8 2 30 7 10 3 28 9 6 4 38 12 6 5 46 9 5 6 50 9 9 7 58 4 12
예 2: 여러 열에 대해 적용() 사용
다음 코드는 apply()를 사용하여 여러 데이터 프레임 열을 제자리에서 변환하는 방법을 보여줍니다.
multiply all values in 'points' and 'rebounds' column by 2 in place df[[' points ', ' rebounds ']] = df[[' points ', ' rebounds ']]. apply ( lambda x: x* 2 ) #view updated DataFrame df points assists rebounds 0 50 5 22 1 24 7 16 2 30 7 20 3 28 9 12 4 38 12 12 5 46 9 10 6 50 9 18 7 58 4 24
예 3: 모든 열에 대해 적용() 사용
다음 코드는 apply()를 사용하여 데이터 프레임의 모든 열을 제자리에서 변환하는 방법을 보여줍니다.
#multiply values in all columns by 2 df = df. apply ( lambda x: x* 2 ) #view updated DataFrame df points assists rebounds 0 50 10 22 1 24 14 16 2 30 14 20 3 28 18 12 4 38 24 12 5 46 18 10 6 50 18 18 7 58 8 24
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 기능을 수행하는 방법을 설명합니다.
Pandas에서 열의 합계를 계산하는 방법
Pandas에서 열의 평균을 계산하는 방법
Pandas에서 열의 최대값을 찾는 방법