首页 > 解决方案 > 在python中用中位数替换异常值的麻烦

问题描述

for col in ('DiabetesPedigreeFunction','Insulin'):
    Q1=df[col].quantile(0.25)
    Q3=df[col].quantile(0.75)

    IQR=Q3-Q1

    upper_limit= Q3+1.5*IQR
    lower_limit= Q1-1.5*IQR

    db_median= float(df[col].median())
    In_median= float(df[col].median())

    df[col]=np.where(df[col]>upper_limit,db_median,df[col])
    df[col]=np.where(df[col]>upper_limit,In_median,df[col])                                     

代码运行良好,但是,使用箱线图检查...异常值仍然存在,也使用.describe()...异常值仍然被注意到。

任何帮助请

标签: pythonpandasdata-cleaningoutliers

解决方案


在此处输入图像描述 使用后发布的代码

>>> list_cols = ['DiabetesPedigreeFunction','Insulin']
>>> df[list_cols] = np.where(((df[list_cols] - df[list_cols].mean()) /     df[list_cols].std()).abs() >= 3, df[list_cols].median(), df[list_cols])

结果与我之前的代码相似...查看图片

>>> df["DiabetesPedigreeFunction"].describe()
count    768.000000
mean       0.449800
std        0.279715
min        0.078000
25%        0.243750
50%        0.371750
75%        0.602000
max        1.461000
Name: DiabetesPedigreeFunction, dtype: float64

推荐阅读