Pandas: factorize()를 사용하여 문자열을 숫자로 인코딩하는 방법
pandas Factorize() 함수를 사용하여 문자열을 숫자 값으로 인코딩할 수 있습니다.
다음 메서드를 사용하여 pandas DataFrame의 열에 Factorize() 함수를 적용할 수 있습니다.
방법 1: 열 인수분해
df[' col1 '] = pd. factorize (df[' col '])[0]
방법 2: 요인별 열
df[[' col1 ', ' col3 ']] = df[[' col1 ', ' col3 ']]. apply ( lambda x: pd.factorize (x)[ 0 ])
방법 3: 모든 열 인수분해
df = df. apply ( lambda x: pd.factorize (x)[ 0 ])
다음 예에서는 다음 pandas DataFrame에서 각 메서드를 사용하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' conf ': ['West', 'West', 'East', 'East'], ' team ': ['A', 'B', 'C', 'D'], ' position ': ['Guard', 'Forward', 'Guard', 'Center'] }) #view DataFrame df conf team position 0 West A Guard 1 West B Forward 2 East C Guard 3 East D Center
예 1: 열 인수분해
다음 코드는 DataFrame에서 열을 인수분해하는 방법을 보여줍니다.
#factorize the conf column only df[' conf '] = pd. factorize (df[' conf '])[ 0 ] #view updated DataFrame df conf team position 0 0 A Guard 1 0 B Forward 2 1 C Guard 3 1 D Center
‘conf’ 열만 인수분해되었습니다.
“West”였던 모든 값은 이제 0이고 “East”였던 모든 값은 이제 1입니다.
예 2: 요인별 열
다음 코드는 DataFrame에서 특정 열을 인수분해하는 방법을 보여줍니다.
#factorize conf and team columns only df[[' conf ', ' team ']] = df[[' conf ', ' team ']]. apply ( lambda x: pd.factorize (x)[ 0 ]) #view updated DataFrame df conf team position 0 0 0 Guard 1 0 1 Forward 2 1 2 Guard 3 1 3 Center
“conf” 및 “team” 열이 모두 고려되었습니다.
예 3: 모든 열을 인수분해
다음 코드는 DataFrame의 모든 열을 인수분해하는 방법을 보여줍니다.
#factorize all columns df = df. apply ( lambda x: pd.factorize (x)[ 0 ]) #view updated DataFrame df conf team position 0 0 0 0 1 0 1 1 2 1 2 0 3 1 3 2
모든 열이 인수분해되었습니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas DataFrame 열을 문자열로 변환하는 방법
Pandas에서 범주형 변수를 숫자로 변환하는 방법
Pandas DataFrame 열을 정수로 변환하는 방법