【问题标题】:How to handle numerical variables in categorical imputer transformer?如何处理分类输入转换器中的数值变量?
【发布时间】:2021-08-22 20:34:12
【问题描述】:

我有一个包含分类值的列 grade 的数据框。我的问题是,值的类型是float 而不是object

import pandas as pd
import numpy as np

df = pd.DataFrame(
 {
 "key": ["K0", "K1", "K2", "K3", "K4"],
 "grade": [1.0, 2.0, 2.0, np.nan, 3.0],
 }
)

df = 
   key  grade
0   K0  1.0
1   K1  2.0
2   K2  2.0
3   K3  NaN
4   K4  3.0

grade 列中有缺失值。我想通过使用基于 sklearn 的feature-engine 来用最常见的值估算缺失值。 Feature-engine包括广泛使用的缺失数据插补方法,如均值和中值插补、频繁类别插补、随机样本插补等。

安装和加​​载库:

! pip install feature-engine

from feature_engine.imputation import CategoricalImputer

应用插补:

# set up the imputer
imputer = CategoricalImputer(variables=['grade'], imputation_method='frequent')

# fit the imputer
imputer.fit(df)

# transform the data
df = imputer.transform(df)

df.head()

我收到以下TypeError

TypeError: Some of the variables are not categorical. Please cast them as object before calling this transformer

我理解错误,但我不明白为什么会出现。根据docsfeature-engine可以用这个转换器处理数值变量。

我的问题是:

  1. 如何使用相同的变压器解决此问题?我误解了文档吗?
  2. 如果这个转换器不起作用,您还有什么建议的解决方案?

【问题讨论】:

    标签: pandas scikit-learn feature-extraction categorical-data imputation


    【解决方案1】:

    在使用 imputer 之前,只需将等级列的dtype 更改为object

    df = pd.DataFrame(
     {
     "key": ["K0", "K1", "K2", "K3", "K4"],
     "grade": [1.0, 2.0, 2.0, np.nan, 3.0],
     }
    )
    
    df["grade"] = df.grade.astype("object")
    
    imputer = CategoricalImputer(variables=['grade'], imputation_method='frequent')
    imputer.fit(df)
    df = imputer.transform(df)
    
    df.head()
    
        key  grade
    0   K0   1.0
    1   K1   2.0
    2   K2   2.0
    3   K3   2.0
    4   K4   3.0
    

    如果您在估算使用后更喜欢等级的 dtype 为字符串/对象,

    imputer = CategoricalImputer(variables=['grade'],
                                 imputation_method='frequent',
                                 return_object=True)
    
    # this returns
    
        key  grade
    0   K0   1
    1   K1   2
    2   K2   2
    3   K3   2
    4   K4   3 
    

    【讨论】:

      【解决方案2】:

      CategoricalImputer 仅用于估算分类变量。这就是为什么默认情况下它只适用于 object 或 categorical 类型的变量。

      但是,在某些情况下,数值变量希望被视为分类变量。在旧版本的包中,为了做到这一点,我们需要按照 Abhi 的描述将变量的格式更改为对象。

      从 1.1 版开始,您可以通过在转换器中设置参数 ignore_format=True 直接使用 CategoricalImputer 估算数值变量。

      【讨论】:

        猜你喜欢
        • 2020-05-22
        • 2020-04-05
        • 1970-01-01
        • 1970-01-01
        • 2019-07-17
        • 2018-09-13
        • 1970-01-01
        • 1970-01-01
        • 2014-09-02
        相关资源
        最近更新 更多