python 用平均值替换离群值

d7v8vwbk  于 2023-11-15  发布在  Python
关注(0)|答案(2)|浏览(162)

我有下面的函数,将删除离群值,但我想在同一列中用平均值替换它们

  1. def remove_outlier(df_in, col_name):
  2. q1 = df_in[col_name].quantile(0.25)
  3. q3 = df_in[col_name].quantile(0.75)
  4. iqr = q3-q1 #Interquartile range
  5. fence_low = q1-1.5*iqr
  6. fence_high = q3+1.5*iqr
  7. df_out = df_in.loc[(df_in[col_name] > fence_low) & (df_in[col_name] < fence_high)]
  8. return df_out

字符串

jucafojl

jucafojl1#

让我们尝试一下。根据您的标准识别离群值,然后直接将列的平均值分配给那些不是离群值的记录。
一些测试数据:

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame({'a': range(10), 'b': np.random.randn(10)})
  4. # These will be our two outlier points
  5. df.iloc[0] = -5
  6. df.iloc[9] = 5
  7. >>> df
  8. a b
  9. 0 -5 -5.000000
  10. 1 1 1.375111
  11. 2 2 -1.004325
  12. 3 3 -1.326068
  13. 4 4 1.689807
  14. 5 5 -0.181405
  15. 6 6 -1.016909
  16. 7 7 -0.039639
  17. 8 8 -0.344721
  18. 9 5 5.000000
  19. def replace_outlier(df_in, col_name):
  20. q1 = df_in[col_name].quantile(0.25)
  21. q3 = df_in[col_name].quantile(0.75)
  22. iqr = q3-q1 #Interquartile range
  23. fence_low = q1-1.5*iqr
  24. fence_high = q3+1.5*iqr
  25. df_out = df.copy()
  26. outliers = ~df_out[col_name].between(fence_low, fence_high, inclusive=False)
  27. df_out.loc[outliers, col_name] = df_out.loc[~outliers, col_name].mean()
  28. return df_out
  29. >>> replace_outlier(df, 'b')
  30. a b
  31. 0 -5 -0.106019
  32. 1 1 1.375111
  33. 2 2 -1.004325
  34. 3 3 -1.326068
  35. 4 4 1.689807
  36. 5 5 -0.181405
  37. 6 6 -1.016909
  38. 7 7 -0.039639
  39. 8 8 -0.344721
  40. 9 5 -0.106019

字符串
我们可以检查填充值是否等于所有其他列值的平均值:

  1. >>> df.iloc[1:9]['b'].mean()
  2. -0.10601866399896176

展开查看全部
qmb5sa22

qmb5sa222#

很好的函数!然而,当我传递参数并运行它时,在df_out.loc[outliers, col_name] = df_out.loc[~outliers, col_name].mean()处发生以下错误。
“FutureWarning:设置不兼容dtype的项已被弃用,并将在将来的pandas错误中引发。”
我只是把平均值传递给新变量ave,并把它赋给df_out.loc[outliers, col_name],然后它就可以工作了。

  1. def replace_outlier(df_in, col_name):
  2. q1 = df_in[col_name].quantile(0.25)
  3. q3 = df_in[col_name].quantile(0.75)
  4. iqr = q3-q1 #Interquartile range
  5. fence_low = q1-1.5*iqr
  6. fence_high = q3+1.5*iqr
  7. df_out = df.copy()
  8. outliers = ~df_out[col_name].between(fence_low, fence_high, inclusive=False)
  9. ave = df_out.loc[~outliers, col_name].mean()
  10. df_out.loc[outliers, col_name] = ave
  11. return df_out

字符串
我的pandas版本是2.1.0。

展开查看全部

相关问题