【问题标题】:replace outliers in a dataframe with the theoretical min/max用理论最小值/最大值替换数据框中的异常值
【发布时间】:2020-07-26 18:01:39
【问题描述】:

我有一个数据框,并被要求用理论最小值/最大值替换数据框中的异常值。但是,我不确定这意味着什么。

我想我已经计算出了理论上的最小值/最大值--

outliers = pd.DataFrame(columns=['min', 'count below', 'max', 'count above'])

for col in df:
  if pd.api.types.is_numeric_dtype(df[col]) and (len(df[col].value_counts()) > 0) and not all(df[col].value_counts().index.isin([0, 1])):

    q1 = df[col].quantile(.25)
    q3 = df[col].quantile(.75)
    min = q1 - (1.5 * (q3 - q1))
    max = q3 + (1.5 * (q3 - q1))

    outliers.loc[col] = (min, df[col][df[col] < min].count(), max, df[col][df[col] > max].count())

这些是我的数据框的几行:

    age sex cp  trestbps    chol    fbs restecg thalach exang   oldpeak slope   ca  thal    num
  0 28  1   2        130    132       0       2 185         0   0.0       NaN   NaN  NaN    0
  1 29  1   2        120    243       0       0 160         0   0.0       NaN   NaN  NaN    0
  2 29  1   2        140    NaN       0       0 170         0   0.0       NaN   NaN  NaN    0
  3 30  0   1        170    237       0       1 170         0   0.0       NaN   NaN    6    0
  4 31  0   2        100    219       0       1 150         0   0.0       NaN   NaN  NaN    0
  5 32  0   2        105    198       0       0 165         0   0.0       NaN   NaN  NaN    0
  .
  .
  .

fbs 还包含一些值的1

exang 还包含一些值的1

oldpeak 还包含03 之间的一些浮点数

slope 主要是NaN,但也包含12 一些值

thal 主要是 NaN,但也包含 367 的某些值

num 还包含 1 几乎一半的值

所以,现在我不确定如何用理论最小值/最大值替换异常值。

【问题讨论】:

  • 什么是“理论最小值/最大值”?这取决于“理论”,并且需要了解变量的含义和学科领域。最大年龄是多少?最小年龄为 0,但如果这些是汽车司机,则可能会更高。

标签: python pandas dataframe statsmodels outliers


【解决方案1】:

对于您的目的,您将不得不弄清楚什么是异常值。我是程序员而不是统计学家,但我怀疑任何超出理论最小值/最大值的东西都符合要求。

至于实际替换异常值...您可能想查看这篇文章的答案。 Conditional Replace Pandas

话虽如此,下面的代码可能会让你继续前进。

df.loc[df[col] > outliers.loc[col]['max'], df[col]] = outliers.loc[col]['max']
df.loc[df[col] < outliers.loc[col]['min'], df[col]] = outliers.loc[col]['min']

重新阅读该问题,听起来您可能正在寻找有关什么构成异常值以及何时有足够的数据具有统计意义的更多信息。如果是这种情况:请考虑在您的问题中添加一些额外的标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多