gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:40 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com