我已经在Pandas数据框中为某些列安装了Onehotencoder:
{ 'country', 'female', 'at_weekend' }
现在,我想在单个字典上使用此Onehotencoder
{ 'country': 'US', 'female': True, 'at_weekend': True }
约束是我不能使用熊猫来转换这本词典。但是,我当然可以使用Numpy和Scikit进行学习。
这是我尝试过的方法,不起作用:
object_dict = { 'country': 'US', 'female': True, 'at_weekend': True }
a = np.array(object_dict)
b = one_hot_encoder.transform(a.reshape(1,-1))
我收到此错误
TypeError:不可哈希类型:'dict'
从object_dict
中提取值(按照训练的顺序,然后使用transform
:]
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({'country':['US', 'UK'], 'female': [True, False], 'at_weekend':[True,False]})
at_weekend country female
0 True US True
1 False UK False
ohe = OneHotEncoder(sparse=False)
ohe.fit(df)
object_dict = {'country': 'US', 'female': True, 'at_weekend': True}
arr = np.array([object_dict[k] for k in df.columns], dtype=object)
ohe.transform(arr.reshape(1, -1))
输出:
array([[0., 1., 0., 1., 0., 1.]])