2017-12-30 6 views
1

데이터 프레임의 형태로 콘텐츠 스트림을 받고 있습니다. 각 배치는 열의 값이 다릅니다.값을 변경하여 데이터 프레임을 일관되게 핫 인코딩합니까?

day1_data = {'state': ['MS', 'OK', 'VA', 'NJ', 'NM'], 
      'city': ['C', 'B', 'G', 'Z', 'F'], 
      'age': [27, 19, 63, 40, 93]} 

와 같은 다른 하나 :

day2_data = {'state': ['AL', 'WY', 'VA'], 
      'city': ['A', 'B', 'E'], 
      'age': [42, 52, 73]} 

어떻게 열이 뜨거운 열 일관된 수를 반환하는 방식으로 인코딩 할 수 있습니다 예를 들어 하나 개의 배치처럼 보일 수 있습니다? 나는 배치의 각 팬더의 get_dummies()를 사용하는 경우

, 그것은 열을 다른 수의 반환

df1 = pd.get_dummies(pd.DataFrame(day1_data)) 
df2 = pd.get_dummies(pd.DataFrame(day2_data)) 

len(df1.columns) == len(df2.columns) 

내가 각 열에 대한 모든 가능한 값을 얻을 수 있습니다, 문제는 그 정보와 짝수 일일 일괄 처리마다 하나의 핫 인코딩을 생성하는 가장 간단한 방법은 무엇입니까? 그래서 열의 수가 일관성이 있습니까?

+0

두 데이터 소스 모두 '연령', '도시'및 '\t'상태 '같은 열을 갖습니다. 항상 그렇습니까? 그렇지 않은 경우 다른 열이 포함 된 좀 더 사실적인 예를 제공하십시오. –

+1

흥미로운 질문입니다. 특정 열에 미리 포함될 수있는 모든 값을 알고 있습니까? – akilat90

+1

그냥 연결 한 다음 인형 가져 오기를 호출하지 않는 이유는 무엇입니까? –

답변

2

가능한 모든 값을 미리 알고 있기 때문에 좋습니다. 다음은 약간 해킹 된 방법입니다.

import numpy as np 
import pandas as pd 

# This is a one time process 
# Keep all the possible data here in lists 
# Can add other categorical variables too which have this type of data 
all_possible_states= ['AL', 'MS', 'MS', 'OK', 'VA', 'NJ', 'NM', 'CD', 'WY'] 
all_possible_cities= ['A', 'B', 'C', 'D', 'E', 'G', 'Z', 'F'] 

# Declare our transformer class 
from sklearn.base import BaseEstimator, TransformerMixin 
from sklearn.preprocessing import LabelEncoder, OneHotEncoder 

class MyOneHotEncoder(BaseEstimator, TransformerMixin): 

    def __init__(self, all_possible_values): 
     self.le = LabelEncoder() 
     self.ohe = OneHotEncoder() 
     self.ohe.fit(self.le.fit_transform(all_possible_values).reshape(-1,1)) 

    def transform(self, X, y=None): 
     return self.ohe.transform(self.le.transform(X).reshape(-1,1)).toarray() 

# Allow the transformer to see all the data here 
encoders = {} 
encoders['state'] = MyOneHotEncoder(all_possible_states) 
encoders['city'] = MyOneHotEncoder(all_possible_cities) 
# Do this for all categorical columns 

# Now this is our method which will be used on the incoming data 
def encode(df): 

    tup = (encoders['state'].transform(df['state']), 
      encoders['city'].transform(df['city']), 
      # Add all other columns which are not to be transformed 
      df[['age']]) 

    return np.hstack(tup) 

# Testing: 
day1_data = pd.DataFrame({'state': ['MS', 'OK', 'VA', 'NJ', 'NM'], 
     'city': ['C', 'B', 'G', 'Z', 'F'], 
     'age': [27, 19, 63, 40, 93]}) 

print(encode(day1_data)) 
[[ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 
    0. 0. 27.] 
[ 0. 0. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 0. 
    0. 0. 19.] 
[ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 
    1. 0. 63.] 
[ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 
    0. 1. 40.] 
[ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 1. 
    0. 0. 93.]] 


day2_data = pd.DataFrame({'state': ['AL', 'WY', 'VA'], 
      'city': ['A', 'B', 'E'], 
      'age': [42, 52, 73]}) 

print(encode(day2_data)) 
[[ 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 
    0. 0. 42.] 
[ 0. 0. 0. 0. 0. 0. 0. 1. 0. 1. 0. 0. 0. 0. 
    0. 0. 52.] 
[ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 
    0. 0. 73.]] 

의견을 검토하고 여전히 문제가 있다면 저에게 물어보십시오.

관련 문제