异常值分析Python:有better/more有效的方法吗?

Outlier Analysis Python: Is there a better/more efficient way?

我正尝试在 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']), :]

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

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])