【问题标题】:trouble Replacing outliers with Median in python在python中用中位数替换异常值的麻烦
【发布时间】:2025-11-22 13:45:01
【问题描述】:
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()...异常值仍然存在。

任何帮助请

【问题讨论】:

    标签: python pandas data-cleaning outliers


    【解决方案1】:

    enter image description here 使用后贴出的代码

    >>> 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
    

    【讨论】:

    • 数据需要被清理,因为一些变量充满了零(0)。例如胰岛素,患者的 BMI 不能为零,所以它必须用 Nan 替换,然后使用“.replace”函数的平均值/中位数......然后我们进入数据倾斜程度的部分......事实上充满异常值。
    最近更新 更多