【问题标题】:Why didn't this code replace the outliers in my columns with the mean?为什么这段代码没有用平均值替换我列中的异常值?
【发布时间】:2021-03-27 23:49:26
【问题描述】:
   all_data = all_data.where(np.abs(stats.zscore(all_data)) < 1.5, np.nan)
all_data = all_data.fillna(all_data.mean())

#count the outliers in each column (AGAIN)
Q1 = all_data.quantile(0.25)
Q3 = all_data.quantile(0.75)
IQR = Q3 - Q1
((all_data < (Q1 - 1.5 * IQR)) | (all_data > (Q3 + 1.5 * IQR))).sum()

我尝试使用上面的代码删除数据框中的异常值。然后我计算了每列(之前和之后)的异常值,并没有太大差异。为什么上面的代码没有删除异常值?这是输出(左边是列名,右边是列的异常值)

 f1        0
f2        0
f3     5696
f4     2885
f5        0
f6        0
f7     9969
f8     4405
f9        0
f10    5675
f11       0
f12    5546
f13    4378
f14    2231
f15    3774
f16    2607
f17       0
f18       0
f19    3388
f20       0
f21       0
f22       0
f23    5276
f24       0
dtype: int64

【问题讨论】:

  • 它在“#count the outliers in each column (AGAIN)”下的帖子中

标签: pandas dataframe outliers


【解决方案1】:

您可以将outliers 替换为NaN,然后用列的平均值填充NaN

df = df.where(np.abs(stats.zscore(df)) < 1.5, np.nan)
df = df.fillna(df.mean())

【讨论】:

  • 嗨!谢谢我试过了,但异常值仍然没有减少。知道为什么吗?我更新了我的帖子。
  • @SofiaRValdez 用np.abs(stats.zscore(df)) &lt; 3判断outliersoutliersTrue还是False?通过使用where(),我将False 视为outliers。另外我在计算列的平均值时包含outliers 值,这是你想要的吗?
  • 是的,我使用您的代码删除异常值/替换为平均值。但是,如果您看到我上面发布的列,由于某种原因,我的所有列中仍然存在一些异常值
  • @SofiaRValdez 在计算列的平均值时是否要包含outliers 值?
  • 不,我不想在平均值中包含异常值
猜你喜欢
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 2019-05-01
  • 1970-01-01
相关资源
最近更新 更多