我正在使用Python 3.5,根据train.csv中的数据预测test.csv中的一些数据。在执行数据挖掘时,我转换train.csv的行和列,这非常好。但当对test.csv执行同样的操作时,它会给出一个:
类型错误:无序类型:float()>str()
train = pd.read_csv('train.csv', header = 0, parse_dates = True, low_memory= False)
test = pd.read_csv('test.csv' , header =0, parse_dates = True, low_memory= False)
le = preprocessing.LabelEncoder()
train.Category = le.fit_transform(train.Category)
train.DayOfWeek = le.fit_transform(train.DayOfWeek)
train.PdDistrict = le.fit_transform(train.PdDistrict)
错误部分
test.DayOfWeek = le.fit_transform(test.DayOfWeek)
test.PdDistrict = le.fit_transform(test.PdDistrict)
两个问题。您不应该对多个列重复使用同一个LabelEncoder
。否则,您将丢失映射,并且无法转换测试数据。
category_le = preprocessing.LabelEncoder()
day_of_week_le = preprocessing.LabelEncoder()
pd_district_le = preprocessing.LabelEncoder()
train_category = category_le.fit_transform(train.Category)
train_day_of_week = day_of_week_le.fit_transform(train.DayOfWeek)
train_pd_district = pd_district_le.fit_transform(train.PdDistrict)
train_X = np.hstack([train_category_mat, train_day_of_week_mat, pd_district_le])
test_category = category_le.transform(test.Category)
test_day_of_week = day_of_week_le.transform(test.DayOfWeek)
test_pd_district = pd_district_le.transform(test.PdDistrict)
这里只是一个快速的代码片段,可以帮助其他正在搜索的人处理无序类型错误。
这个问题(你已经发现了)被粘贴在这里,正如在另一个论坛帖子中所发现的那样:"因为我试图编码的列中基本上有混合类型。我终于能够通过将每个'object'类型的列转换为'str'类型来解决这个问题,这就停止了错误。"
处理完丢失的数据后,可以使用.astype(str)
属性,使用此代码迭代与一组数据类型匹配的列,并将它们转换为字符串。
#REPLACE NAN WITH 0
X_train.fillna(0.0, inplace=True)
#GET LIST OF COLUMNS TO ENCODE
cols_to_enc = list(X_train.select_dtypes(include=['category', 'object']))
for feature in cols_to_enc:
try:
#CONVERT VALUE TO STRING (TO AVOID UNORDERED TYPE ERRORS)
X_train[feature] = X_train[feature].astype(str)
except Exception as err:
print('cannot convert: %s' % feature)
print(err)