Pandas에서 범주형 변수를 숫자로 변환하는 방법


다음 기본 구문을 사용하여 Pandas DataFrame에서 범주형 변수를 숫자 변수로 변환할 수 있습니다.

 df[' column_name '] = pd. factorize (df[' column_name '])[0]

다음 구문을 사용하여 DataFrame의 각 범주형 변수를 숫자 변수로 변환할 수도 있습니다.

 #identify all categorical variables
cat_columns = df. select_dtypes ([' object ']). columns

#convert all categorical variables to numeric
df[cat_columns] = df[cat_columns]. apply ( lambda x: pd.factorize (x)[ 0 ])

다음 예에서는 이 구문을 실제로 사용하는 방법을 보여줍니다.

예 1: 범주형 변수를 숫자로 변환

다음과 같은 팬더 DataFrame이 있다고 가정합니다.

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   ' position ': ['G', 'G', 'F', 'G', 'F', 'C', 'G', 'F', 'C'],
                   ' points ': [5, 7, 7, 9, 12, 9, 9, 4, 13],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12, 10]})

#view DataFrame
df

team position points rebounds
0 A G 5 11
1 A G 7 8
2 A F 7 10
3 B G 9 6
4 B F 12 6
5 B C 9 5
6 C G 9 9
7 C F 4 12
8 C C 13 10

다음 구문을 사용하여 “팀” 열을 숫자로 변환할 수 있습니다.

 #convert 'team' column to numeric
df[' team '] = pd. factorize (df[' team '])[ 0 ]

#view updated DataFrame
df

team position points rebounds
0 0 G 5 11
1 0 G 7 8
2 0 F 7 10
3 1 G 9 6
4 1 F 12 6
5 1 C 9 5
6 2 G 9 9
7 2 F 4 12
8 2 C 13 10

변환이 진행된 방법은 다음과 같습니다.

  • 값이 ” A “인 각 팀은 0 으로 변환되었습니다.
  • 값이 ” B “인 각 팀은 1 로 변환되었습니다.
  • C ” 값을 가진 각 팀은 2 로 변환되었습니다.

예 2: 여러 범주형 변수를 숫자 값으로 변환

다음과 같은 pandas DataFrame이 있다고 다시 가정해 보겠습니다.

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   ' position ': ['G', 'G', 'F', 'G', 'F', 'C', 'G', 'F', 'C'],
                   ' points ': [5, 7, 7, 9, 12, 9, 9, 4, 13],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12, 10]})

#view DataFrame
df

        team position points rebounds
0 A G 5 11
1 A G 7 8
2 A F 7 10
3 B G 9 6
4 B F 12 6
5 B C 9 5
6 C G 9 9
7 C F 4 12
8 C C 13 10

다음 구문을 사용하여 DataFrame의 각 범주형 변수를 숫자 변수로 변환할 수 있습니다.

 #get all categorical columns
cat_columns = df. select_dtypes ([' object ']). columns

#convert all categorical columns to numeric
df[cat_columns] = df[cat_columns]. apply ( lambda x: pd.factorize (x)[ 0 ])

#view updated DataFrame
df

	team position points rebounds
0 0 0 5 11
1 0 0 7 8
2 0 1 7 10
3 1 0 9 6
4 1 1 12 6
5 1 2 9 5
6 2 0 9 9
7 2 1 4 12
8 2 2 13 10

두 개의 범주형 열(팀 및 위치)은 모두 숫자로 변환되었지만 포인트 및 리바운드 열은 동일하게 유지되었습니다.

참고 : Pandas Factorize() 함수에 대한 전체 문서는 여기에서 찾을 수 있습니다.

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Pandas DataFrame 열을 문자열로 변환하는 방법
Pandas DataFrame 열을 정수로 변환하는 방법
Pandas DataFrame에서 문자열을 부동 소수점으로 변환하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다