데이터분석/데테_인공지능

Nominal Attribute (LabelEncoder, fit, transform)

하연01 2021. 4. 28. 01:03

< Nominal Attributes > 

nominal attribute를 다루는 데 가장 유용한 method : LabelEncoder, fit, transform 

- Nominal Attribute ("names of thing") 처리 

→ 카테고리컬 데이터 중 nominal attribute를 잘 처리할 수 있는 것 = LabelEncoer()

from sklearn import preprocessing 
le = preprocessing.LabelEncoder()

le.fit(["paris","paris","tokyo","amsterdam"])
print(le.classes_)
print(type(le.classes_), "\n")

data = le.transform(["paris","paris","tokyo","amsterdam"])
print(data)
print(type(data), "\n")

original = le.inverse_transform([2, 2, 1])
print(original)
print(type(data))

fit : 각자 라벨링, 순서를 정해줌, 스펠링 순서로 인코딩을 가지게 된다. 

( amsterdam - paris - tokyo) 

transform: 데이터 변환

inverse_transform : 라벨을 입력할테니 데이터를 달라 

 

 

 

# 영어 소문자 transformation 

from sklearn import preprocessing 
le = preprocessing.LabelEncoder()

str = []
for i in range(ord('a'), ord('z')+1):
    str.append(chr(i))
print(str)

le.fit(str)
data = le.transform(['q','a','z'])
print(data)

첫 리스트에는 영어 소문자 데이터

[16 0 25] : q는 16번째, a는 0번째, z는 25번째 

 

 

# DataFrame 변환 

from sklearn import preprocessing 
import pandas as pd 

le = preprocessing.LabelEncoder()
df = pd.DataFrame({'A':['a','b','b','c','a'],
                  'B':['x','y','x','y','x']})

# fit_transform : fit과 transform을 동시에 처리 
# df.apply : dataframe에서 인자로 주어진 함수를 각 컬럼에 적용하는 함수 
data = df.apply(le.fit_transform)
print(data)
print(type(data))

fit_transform : fit과 transform을 동시에 처리 (인코딩해서 숫자부여 할래)

df.apply : dataframe에서 인자로 주어진 함수를 각 컬럼에 적용하는 함수 

→ A, B 두 컬럼을 동시에 fit_transform 처리

출력한 표는 데이터프레임 형식 'a', 'b', 'c' → 0, 1, 2'x', 'y' → 0, 1 로 변환