简体   繁体   English

使用 sci-kit learn 仅输入数值

[英]Imputing only the numerical values using sci-kit learn

So, I have a DataFrame that contains a mix of both Categorical and Numerical values that is currently 12345 rows by 171 columns.所以,我有一个 DataFrame,它包含分类和数值的混合,目前是12345行 x 171列。

I have missing values in both the Categorical variable and the Numerical where I would like to impute the values.我在分类变量和数值中都有缺失值,我想在其中估算这些值。 For the Numerical columns I am doing the following;对于数值列,我正在执行以下操作;

import pandas as pd
import numpy as np

data = pd.read_csv('filepath')

from sklearn.preprocessing import Imputer
imp = Imputer(missing_values=np.nan, strategy='mean', axis=0)
data = imp.fit_transform(data)

I then get the following error然后我收到以下错误

ValueError: could not convert string to float: 'USD'

This I understand is because I am using sci-kit learns imputer with strategy = mean which is not compatible with Categorical variables.我理解这是因为我使用 sci-kit 学习带有strategy = mean imputer,这与 Categorical 变量不兼容。 I would rather not have to go through each column and manually pull out the Numerical values so I am looking for a way that I can perform this imputation only on the Numerical columns.我宁愿不必遍历每一列并手动拉出数值,所以我正在寻找一种方法,我可以只对数值列执行此插补。

If you use panda's categorical encoding functionality, this can all be handled pretty simply.如果您使用熊猫的分类编码功能,这一切都可以非常简单地处理。 I however rarely find myself with properly encoded data, and would rather have a robust solution than rely on pure pandas.然而,我很少发现自己拥有正确编码的数据,并且宁愿拥有一个强大的解决方案而不是依赖纯熊猫。

Here's what I would do.这就是我要做的。

categorical_columns = []
numeric_columns = []
for c in data.columns:
    if data[c].map(type).eq(str).any(): #check if there are any strings in column
        categorical_columns.append(c)
    else:
        numeric_columns.append(c)

#create two DataFrames, one for each data type
data_numeric = data[numeric_columns]
data_categorical = pd.DataFrame(data[categorical_columns])


from sklearn.preprocessing import Imputer
imp = Imputer(missing_values=np.nan, strategy='mean', axis=0)
data_numeric = pd.DataFrame(imp.fit_transform(data_numeric), columns = data_numeric.columns) #only apply imputer to numeric columns


#you could do something like one-hot-encoding of data_categorical here

#join the two masked dataframes back together
data_joined = pd.concat([data_numeric, data_categorical], axis = 1)

You can select all numeric columns using select_dtypes method:您可以使用 select_dtypes 方法选择所有数字列:

numeric_columns = data.select_dtypes(include='number').columns
imp = Imputer(missing_values=np.nan, strategy='mean', axis=0)
data[numeric_columns] = pd.DataFrame(imp.fit_transform(data[numeric_columns]), columns=numeric_columns)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM