【发布时间】:2019-01-30 18:19:36
【问题描述】:
我有一个包含数值、分类和 NaN 值的数据框。
customer_class B C
0 OM1 1 2.0
1 NaN 6 1.0
2 OM1 9 NaN
....
我需要一个 LabelEncoder 将我的缺失值保持为“NaN”,以便之后使用 Imputer。
所以我想使用此代码通过保持 NaN 值来编码我的数据帧。
这里是代码:
class LabelEncoderByCol(BaseEstimator, TransformerMixin):
def __init__(self,col):
#List of column names in the DataFrame that should be encoded
self.col = col
#Dictionary storing a LabelEncoder for each column
self.le_dic = {}
for el in self.col:
self.le_dic[el] = LabelEncoder()
def fit(self,x,y=None):
#Fill missing values with the string 'NaN'
x[self.col] = x[self.col].fillna('NaN')
for el in self.col:
#Only use the values that are not 'NaN' to fit the Encoder
a = x[el][x[el]!='NaN']
self.le_dic[el].fit(a)
return self
def transform(self,x,y=None):
#Fill missing values with the string 'NaN'
x[self.col] = x[self.col].fillna('NaN')
for el in self.col:
#Only use the values that are not 'NaN' to fit the Encoder
a = x[el][x[el]!='NaN']
#Store an ndarray of the current column
b = x[el].get_values()
#Replace the elements in the ndarray that are not 'NaN'
#using the transformer
b[b!='NaN'] = self.le_dic[el].transform(a)
#Overwrite the column in the DataFrame
x[el]=b
#return the transformed D
col = data1['customer_class']
LabelEncoderByCol(col)
LabelEncoderByCol.fit(x=col,y=None)
但是我收到了这个错误: 第846章 --> 847 raise ValueError('%s 未包含在索引中' % str(key[mask])) 第848章 第849章
ValueError: ['OM1' 'OM1' 'OM1' ... 'other' 'EU' 'EUB'] 未包含在索引中
有什么办法解决这个错误吗?
谢谢
【问题讨论】:
标签: python pandas class dataframe