我正在解决一个问题,其中我是 OneHot 编码来自数据帧的一组特征,例如:
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y)
oh = OneHotEncoder(handle_unknown='ignore')
print(X)
a b c
1 one m y
2 two m n
36 three f n
113 one f n
31 two m other
....
oh.fit(X_train)
但是,可能并非所有特征都存在于测试集中。对于这个例子,假设我只有前两列。在这种情况下,编码器将引发错误:
oh.transform(X_test.loc[:,:'b'])
X 中的特征数与拟合数据的特征数不同。拟合数据有 3 个特征,X 有 2 个特征。
有没有办法解决这个问题?理想情况下,我希望丢失的列被忽略(输出中不存在)或设置为NaN
.