python - 异常值分析 Python : Is there a better/more efficient way?

标签 python pandas outliers

我正在尝试使用 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])

关于python - 异常值分析 Python : Is there a better/more efficient way?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47347319/

相关文章:

python - tensorflow cnn 错误 : InvalidArgumentError (see above for traceback): logits and labels must be same size

python - 如何使用pandas比较同一行中多列的单列值?

python - 如何将嵌套 JSON 转换为 CSV

python - 将 DataArray 合并到 xarray 数据集中

python - 使用 Python Requests 在 postman 中做 post 请求

python - pandas:创建 n 个新列来包含最后 n 个值(滚动)

r - 如何从数据框中删除超出变量特定范围的记录? [R]

python - 是否可以屏蔽 scikit 学习管道中的异常值?

R - 在血压曲线中寻找异常值/伪影的方法

python - 对字典的所有值应用函数