【问题标题】:Handling the outliers处理异常值
【发布时间】:2020-11-08 15:01:26
【问题描述】:

我一直在尝试处理特定变量的异常值。我试过以下代码:

for feature in X.columns:
    IQR = X[feature].quantile(0.75) - X[feature].quantile(0.25)
    upper = X[feature].quantile(0.75)+(IQR*1.5)
    lower = X[feature].quantile(0.25) - (IQR-1.5)
    X.loc[X[feature]>upper,feature]=X[feature].median()
    X.loc[X[feature]<lower,feature]=X[feature].median()

X 是一个数据框 upper and lower 表示上边界和下边界。

运行这段代码后,变量中仍有异常值。

【问题讨论】:

    标签: python machine-learning data-science


    【解决方案1】:

    您还可以使用Z-scores 作为对异常值进行分类的衡量标准

    您可以计算 numeric_cols 的 Z 分数

    from scipy.stats import zscore
    numeric_cols = df.select_dtypes(include=[np.number]).columns
    
    # Note that `select_dtypes` returns a data frame. We are selecting only the columns
    
    df_zscore = df[numeric_cols].apply(zscore)
    

    计算 z_scores 后,您可以设置阈值条件来过滤高于该 z-score 值的索引

    threshold = 3
    outlier_column = ### The column to check the outliers on
    
    upper_bound_idx = df_zscore[df_zscore[outlier_column] > threshold].index
    

    您还可以根据异常索引值upper_bound_idx 过滤原始数据框df

    离群值 = df.loc[upper_bound_idx,outlier_column]

    您也可以选择删除异常值索引

    df = df.drop(index=upper_bound_idx)
    

    【讨论】:

      【解决方案2】:

      如果 IQR 和 z 分数不适合您,您可以尝试更高级的方法来检测异常值,例如隔离森林、最小协方差行列式或局部异常值因子...这篇很棒的博文展示了一般使用 sklearn 的要点:blog post

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多