【问题标题】:Impute missing and outlier values as median, excluding the outliers from the calculation of the median将缺失值和异常值估算为中值,从中值计算中排除异常值
【发布时间】:2018-06-29 15:12:30
【问题描述】:

估算缺失值和极值的中值,从中值的计算中排除那些极值。

我想使用中位数进行估算。我想计算不包括极值的中位数。然后我想将这些极端值归为中值。

我有一个这样的数据框:

df = pd.DataFrame({"AAA":[100,NaN,0.0,0.1,4.6]})

   AAA
0  100
1  NaN
2  0.0
3  0.1
4  4.6

我想将观察指数 =0 定义为异常值,因此,将其从插补计算中排除,并插补它的值。

   AAA  impute
0  100    True
1  NaN    True
2  0.0   False
3  0.1   False
4  4.6   False

然后我想在新的 AAA_ 列中估算 NaN 的值

   AAA  impute  AAA_
0  100    True   NaN
1  NaN    True   NaN
2  0.0   False   0.0
3  0.1   False   0.1
4  4.6   False   4.6

因此,我想要一个如下所示的数据框:

   AAA  impute  AAA_
0  100    True   0.1
1  NaN    True   0.1
2  0.0   False   0.0
3  0.1   False   0.1
4  4.6   False   4.6

【问题讨论】:

    标签: pandas scikit-learn data-cleaning


    【解决方案1】:

     1. 将观察指数 =0 定义为异常值,因此将其排除。

    我们首先将df["AAA"] 中的异常值计算为单独的布尔数组(与原始系列的长度相同)。

    outlier = np.where(df["AAA"] >= 100,1,0).astype(bool)
    is_null = np.where(df["AAA"].isnull(),1,0).astype(bool)
    impute = (outlier | is_null)
    

    这会将以下结果作为数据框返回。

    df["impute"] = impute
    
       AAA  impute
    0  100    True
    1  NaN    True
    2  0.0   False
    3  0.1   False
    4  4.6   False
    

    2。仅使用有效值创建特征向量

    然后为我们将用于插补的值创建一个新的特征向量。这是AAA 的子集,具体取决于它是被标记为异常值还是缺失。

    AAA_=np.where(~impute, x.AAA, np.nan)
    
    df["AAA_"] = AAA_
    
       AAA  impute  AAA_
    0  100    True   NaN
    1  NaN    True   NaN
    2  0.0   False   0.0
    3  0.1   False   0.1
    4  4.6   False   4.6
    

    3。估算值

    然后您可以使用 scikit-learn 的 preprocessing.Imputer 估算值。

    median_imputer = preprocessing.Imputer(strategy="median", axis=0)
    AAA_complete = median_imputer.fit_transform(AAA_.reshape(-1, 1))
    

    这会返回答案:

    df["AAA"] = AAA_complete
    
       AAA  impute  AAA_
    0  100    True   0.1
    1  NaN    True   0.1
    2  0.0   False   0.0
    3  0.1   False   0.1
    4  4.6   False   4.6
    

    注意:我知道中位数在面对极端值时是稳健的,但我希望这些值也能被转换。这可以通过更改一行轻松更改为平均值。 median_imputer = preprocessing.Imputer(strategy="median", axis=0)mean_imputer = preprocessing.Imputer(strategy="mean", axis=0)

    【讨论】:

      猜你喜欢
      • 2012-10-03
      • 2019-12-29
      • 2011-06-07
      • 2020-07-21
      • 2014-06-23
      • 2023-02-05
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多