2017-12-20 4 views
0

기계 학습을위한 Python에서 데이터 전처리가 처음입니다. 일부 데이터를 사전 처리하려고합니다. 데이터는 빈 항목과 NaN 항목이있는 많은 범주 형 변수로 구성됩니다. ffil 메서드를 사용하여 빈 또는 NaN 공간을 채우는 중 sklearn LabelEncoder를 사용하여 레이블 인코딩을 한 후 나중에 한 번만 인코딩하면됩니다. 두 개의 다른 코드 세그먼트가 있습니다. 라벨 인코딩을하는 것은 오류를 제공하지 않습니다하지만 여기서 첫 번째는 간단 조금 나는 위에서 언급 한 오류가 발생하고 몇 addintional 프로세스가 두 번째 경우 : 첫 번째 코드 섹션TypeError : 'str'과 'float'인스턴스간에 추가 작업이 추가되면 '>'이 (가) 지원되지 않습니다.

encoder = LabelEncoder() 
for cols in train.keys(): 
    if(cols.startswith('cat')): 
     train[cols].fillna(method='ffill', inplace=True) 
     train[cols].fillna(method='bfill', inplace=True) 
     if train[cols].dtype == 'object': 
      train[cols] = encoder.fit_transform(train[cols]) 
      train = pd.get_dummies(data=train, columns=[cols]) 

두 번째 코드 섹션 :

encoder = LabelEncoder() 
best_fit = SelectKBest(score_func=chi2, k=10) 
for cols in train.keys(): 
    if(cols.startswith('cat')): 
     train[cols].fillna(method='ffill', inplace=True) 
     train[cols].fillna(method='bfill', inplace=True) 
     if train[cols].dtype == 'object': 
      train[cols] = encoder.fit_transform(train[cols]) 
      train_temp = pd.get_dummies(data=train, columns=[cols]) 
      temp_df = train_temp[list(set(train_temp.keys())-set(train.keys()))] 
      fit_temp = best_fit.fit(temp_df, target) 
      features_temp = fit_temp.transform(temp_df) 
      train = train.drop([cols], axis=1) 
      train = pd.concat([train, pd.DataFrame(features_temp)], axis = 1, join='outer') 

역 추적 로그 :

Traceback (most recent call last): 

    File "<ipython-input-1-4efe4593ba69>", line 37, in <module> 
    train[cols] = encoder.fit_transform(train[cols]) 

    File "C:\Continuum\anaconda3\lib\site-packages\sklearn\preprocessing\label.py", line 112, in fit_transform 
    self.classes_, y = np.unique(y, return_inverse=True) 

    File "C:\Continuum\anaconda3\lib\site-packages\numpy\lib\arraysetops.py", line 211, in unique 
    perm = ar.argsort(kind='mergesort' if return_index else 'quicksort') 

TypeError: '>' not supported between instances of 'str' and 'float' 

문제가 해결 : 은 내부 에러처럼 보인다. 기계를 다시 시작하고 스크립트를 다시 실행하면 문제가 해결됩니다.

+1

질문 제목에 넣은 오류 메시지에 대해 질문하는 경우 질문에 전체 추적을 포함하고 게시 한 소스 행을 나타냅니다. – Duncan

+0

@Duncan이 로그를 추가했습니다. 시정 해줘서 고마워. –

답변

1

이 오류는 데이터가 인코더로 전달되는 동안 데이터 형식이 동일해야하며 인코더로 전달할 때 열을 한 dtype로 변환해야하기 때문에 발생합니다.

from sklearn import preprocessing 
encoder = preprocessing.LabelEncoder() 

df = pd.DataFrame({'a':[1,2,3,'NAN','4']}) 

encoder.fit_transform(df['a'].astype(str)) 
#or if you have only numerical datatype then 
#encoder.fit_transform(pd.to_numeric(df['a'],errors='coerce')) 
+0

그러나 첫 번째 섹션에서 올바르게 작동 함 –

+0

솔루션이 작동하지 않았습니까? 시도해 보았 니? 이 줄은'train [cols] .fillna (value = "", inplace = True)'일 수 있습니다. 문자열을 데이터 프레임에 추가하면 숫자가있을 수도 있습니다. – Dark

+0

메모리 문제가있는 것 같습니다. . 기계를 다시 시작한 후 이전에 오류가 발생하여 코드를 실행했습니다. –

관련 문제