如何预处理具有多种类型缺失数据的数据集

How to preprocess a dataset with many types of missing data

我正在尝试做初学者机器学习项目 Big Mart Sales。 该项目的数据集包含多种类型的缺失值(NaN),以及需要更改的值(lf -> Low Fat,reg -> Regular等)

我目前预处理此数据的方法是为每种需要修复的数据类型创建一个输入器:

from sklearn.impute import SimpleImputer as Imputer

# make the values consistent
lf_imputer = Imputer(missing_values='LF', strategy='constant', fill_value='Low Fat')
lowfat_imputer = Imputer(missing_values='low fat', strategy='constant', fill_value='Low Fat')
X[:,1:2] = lf_imputer.fit_transform(X[:,1:2])
X[:,1:2] = lowfat_imputer.fit_transform(X[:,1:2])

# nan for a categorical variable
nan_imputer = Imputer(missing_values=np.nan, strategy='most_frequent')
X[:, 7:8] = nan_imputer.fit_transform(X[:, 7:8])

# nan for a numerical variable
nan_num_imputer = Imputer(missing_values=np.nan, strategy='mean')
X[:, 0:1] = nan_num_imputer.fit_transform(X[:, 0:1])

但是,这种方法非常麻烦。有没有更简洁的方法来预处理这个数据集?

此外,令人沮丧的是 imputer.fit_transform() 需要一个二维数组作为输入,而我只想修复单个列 (1D) 中的值。因此,我总是必须使用我想要修复的列加上它旁边的列作为输入。还有其他方法可以解决这个问题吗?谢谢

以下是我的几行数据:

However, this approach is pretty cumbersome. Is there any neater way to preprocess this data set?

如果你有一个数字列,你可以使用一些方法来填充缺失的数据:

  • 在域内有意义的常量值,例如 0,与所有其他值不同。
  • 来自另一条随机选择的记录的值。
  • 该列的平均值、中值或众数。
  • 另一个预测模型估计的值。

让我们看看它如何计算一列的平均值,例如: 一种方法是使用 pandas:

中的 fillna
X['Name'].fillna(X['Name'].mean(), inplace=True) 

分类数据请看这里:Impute categorical missing values in scikit-learn

有一个 python 包可以以简单的方式为您完成此操作,ctrl4ai

pip install ctrl4ai

from ctrl4ai import preprocessing

preprocessing.impute_nulls(dataset)

Usage: [arg1]:[pandas dataframe],[method(default=central_tendency)]:[Choose either central_tendency or KNN]
Description: Auto identifies the type of distribution in the column and imputes null values
Note: KNN consumes more system mermory if the size of the dataset is huge
Returns: Dataframe [with separate column for each categorical values]