【问题标题】:Outlier Analysis Python: Is there a better/more efficient way?异常值分析 Python:有没有更好/更有效的方法?
【发布时间】:2018-05-01 00:48:55
【问题描述】:

我正在尝试在 Python 中进行异常值分析。由于我有多个长度不同的数据帧,当数据帧有 10 个观察值时,我想扣除尾部和头部的 2.5%,当它有 100 个观察值时扣除 0.25% 等。目前,我有一些似乎可以工作的代码。但是,我仍然觉得它可能会更有效率。这主要是因为最后两行。我觉得过滤器可以在一行中完成。另外,我不确定 .loc 在这里是否有用。也许有更好的方法来做到这一点?有人有建议吗?

这是我的第一个问题,所以如果我的问题有什么可以改进的,请告诉我=)

目前,这是我的代码:

    df_filtered_3['variable'] = df_filtered_3['variable1'] / df_filtered_3['variable2']

    if len(df_filtered_3.index) <= 10:
        low = .025
        high = .0975
    elif len(df_filtered_3.index) <= 100:
        low = .0025
        high = .00975
    elif len(df_filtered_3.index) <= 1000:
        low = .00025
        high = .000975
    elif len(df_filtered_3.index) <= 10000:
        low = .000025
        high = .0000975
    else:
        low = .0000025
        high = .00000975

    quant_df = df_filtered_3.quantile([low, high])
    df_filtered_3 = df_filtered_3.loc[df_filtered_3['variable'] > int(quant_df.loc[low, 'variable']), :]
    df_filtered_3 = df_filtered_3.loc[df_filtered_3['variable'] < int(quant_df.loc[high, 'variable']), :]

【问题讨论】:

  • 你能修复缩进吗?确保突出显示整个选择并按 ctrl-k
  • 感谢您为我更改此设置!我很感激。
  • “我仍然觉得它可能会更有效率”——是什么让你有这样的感觉?它表现不佳吗?如果是这样 - 知道瓶颈在哪里吗?
  • 对不起。我应该澄清一下。我刚刚编辑了问题。
  • 你能发布一个小样本数据框吗?

标签: python pandas outliers


【解决方案1】:

你可以写得更短,但不一定更快:

In [57]: coefs = np.array([.025, .0975])

In [58]: coefs / pd.cut([len(df.index)], [0, 10, 100, 1000, 10000, np.inf], labels=[1, 10, 100, 1000, 10000], right=True)[0]
Out[58]: array([ 0.025 ,  0.0975])

例子:

In [59]: coefs / pd.cut([105], [0, 10, 100, 1000, 10000, np.inf], labels=[1, 10, 100, 1000, 10000], right=True)[0]
Out[59]: array([ 0.00025 ,  0.000975])

In [60]: coefs / pd.cut([1005], [0, 10, 100, 1000, 10000, np.inf], labels=[1, 10, 100, 1000, 10000], right=True)[0]
Out[60]: array([  2.50000000e-05,   9.75000000e-05])

【讨论】:

  • @jezrael,谢谢! OP 正在测试单个数字 (len(df_filtered_3.index)),因此在这种情况下,if ... else ... 块可能会更快
  • 嗯,这主要取决于数据...但我认为通常应该更快
  • 非常感谢。我会试一试的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 2013-11-24
  • 2020-01-08
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
相关资源
最近更新 更多