【问题标题】:Convert a single dictionary to array with a fitted OnehotEncoder使用合适的 OnehotEncoder 将单个字典转换为数组
【发布时间】:2019-10-02 01:56:35
【问题描述】:

我在 pandas 数据框上为某些列安装了 Onehotencoder:

{ 'country', 'female', 'at_weekend' }

现在,我想在单个字典上使用这个 Onehotencoder

{ 'country': 'US', 'female': True, 'at_weekend': True } 

限制是我不能使用 pandas 来转换这本字典。 不过,我当然可以使用 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: unhashable type: 'dict'

【问题讨论】:

    标签: python-3.x scikit-learn one-hot-encoding


    【解决方案1】:

    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.]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 2021-08-10
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多