Python:用中位数替换异常值

15

我有一个Python数据框,其中有一些异常值。我希望用数据的中位数替换它们,前提是这些值不存在。

id         Age
10236    766105
11993       288
9337        205
38189        88
35555        82
39443        75
10762        74
33847        72
21194        70
39450        70

因此,我想用剩余数据集的中位数来替换所有大于75的值,即70,70,72,74,75的中位数。

我正在尝试执行以下操作:

  1. 用0替换所有大于75的值
  2. 将0替换为中位数。

但不知何故,下面的代码无法正常工作。

df['age'].replace(df.age>75,0,inplace=True)
5个回答

30

我认为这就是你要找的,你可以使用 loc 分配值。然后你可以填充 nan。

median = df.loc[df['Age']<75, 'Age'].median()
df.loc[df.Age > 75, 'Age'] = np.nan
df.fillna(median,inplace=True)

你也可以在一行中使用np.where

df["Age"] = np.where(df["Age"] >75, median,df['Age'])

您也可以使用.mask,例如:

df["Age"] = df["Age"].mask(df["Age"] >75, median)

2
更改为 年龄 > 75。 +1 - Ekaba Bisong
很高兴能帮助 @user4943236 - Bharath M Shetty

1

0
我最近尝试的更通用的解决方案是:用整列的中位数替换75,然后按照Bharath建议的类似方法解决问题。
median = float(df['Age'].median())
df["Age"] = np.where(df["Age"] > median, median, df['Age'])

但是在这种情况下,用作阈值的中位数值将受到所有值(包括异常值)的影响。 - Arka Saha

0

你的代码几乎正确,但是还有一些差距。
使用:

df['age']=df['age'].replace(df.age>75,0,inplace=True)

0
有一个用于将异常值替换为中位数的代码,适用于 np.array
def replace_outliers_with_median(err_arr):
    a = err_arr
    med = np.median(a)
    outlierConstant = 1.5
    upper_quartile = np.percentile(a, 80)
    lower_quartile = np.percentile(a, 20)
    IQR = (upper_quartile - lower_quartile) * outlierConstant
    quartileSet = (lower_quartile - IQR, upper_quartile + IQR)
    # Find the outliers with 80% interval and replace them with median value 
    output = np.where((a >= quartileSet[0]) & (a <= quartileSet[1]), a, med)

    return output

例子:

arr =np.array([ [-8.33717,-8.3755,-7.83968,-7.09376, -6.37511,
                 -5.81576,-11.46364,-5.30386,-5.20346,-5.35983,
                 -5.35344,-5.2447,-5.04924,-4.98142,-4.72909,
                  4.86889,-4.95571,-4.93626,-5.17441,-5.18517,
                 -5.30639,-5.36995,-8]])

df = replace_outliers_with_median(arr)

output:

array([[-8.33717, -8.3755 , -7.83968, -7.09376, -6.37511, -5.81576,
        -5.30639, -5.30386, -5.20346, -5.35983, -5.35344, -5.2447 ,
        -5.04924, -4.98142, -4.72909, -5.30639, -4.95571, -4.93626,
        -5.17441, -5.18517, -5.30639, -5.36995, -8.     ]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接