【问题标题】:How do you index outliers in python?你如何在python中索引异常值?
【发布时间】:2018-02-27 14:39:48
【问题描述】:

我正在尝试从 python 列表中删除异常值。我想从原始列表中获取每个异常值的索引值,以便可以从(另一个)对应列表中删除它。

~~简单的例子~~

我的异常值列表:

y = [1,2,3,4,500] #500 is the outlier; has a index of 4

我的对应列表:

x= [1,2,3,4,5] #I want to remove 5, has the same index of 4

我的结果/目标:

y=[1,2,3,4]

x=[1,2,3,4]

这是我的代码,我想用 klist 和 avglatlist 实现同样的效果

import numpy as np

klist=['1','2','3','4','5','6','7','8','4000']
avglatlist=['1','2','3','4','5','6','7','8','9']


klist = np.array(klist).astype(np.float)      
klist=klist[(abs(klist - np.mean(klist))) < (2 * np.std(klist))]

indices=[]
for k in klist:
    if (k-np.mean(klist))>((2*np.std(klist))):
        i=klist.index(k)
        indices.append(i)

print('indices'+str(indices))

avglatlist = np.array(avglatlist).astype(np.float) 


for index in sorted(indices, reverse=True):
    del avglatlist[index]


print(len(klist))
print(len(avglatlist))

【问题讨论】:

  • 定义异常值。你如何识别它?
  • 如果数字减去平均值大于标准差的 2 倍。我在实际编码时遇到了麻烦,而不是定义它。我尝试做的每一种方式都会出错

标签: python python-3.x numpy machine-learning outliers


【解决方案1】:

如何获取列表中每个异常值的索引值?

假设离群值被定义为平均值的 2 个标准差。这意味着您想知道 zscore 的绝对值大于 2 的列表中值的索引。

我会使用 np.where

import numpy as np
from scipy.stats import zscore

klist = np.array([1, 2, 3, 4, 5, 6, 7, 8, 4000])
avglatlist = np.arange(1, klist.shape[0] + 1)

indices = np.where(np.absolute(zscore(klist)) > 2)[0]
indices_filter = [i for i,n in enumerate(klist) if i not in indices]
print(avglatlist[indices_filter])

如果您实际上不需要知道索引,请改用布尔掩码

import numpy as np
from scipy.stats import zscore

klist = np.array([1, 2, 3, 4, 5, 6, 7, 8, 4000])
avglatlist = np.arange(1, klist.shape[0] + 1)

mask = np.absolute(zscore(klist)) > 2
print(avglatlist[~mask])

两种解决方案都打印:

[1 2 3 4 5 6 7 8]

【讨论】:

    【解决方案2】:

    你真的很亲密。您需要做的就是将相同的过滤机制应用于 avglatlist 的 numpy 版本。为了清楚起见,我更改了一些变量名称。

    import numpy as np
    
    klist = ['1', '2', '3', '4', '5', '6', '7', '8', '4000']
    avglatlist = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    
    klist_np = np.array(klist).astype(np.float)
    avglatlist_np = np.array(avglatlist).astype(np.float)    
    
    klist_filtered = klist_np[(abs(klist_np - np.mean(klist_np))) < (2 * np.std(klist_np))]
    avglatlist_filtered = avglatlist_np[(abs(klist_np - np.mean(klist_np))) < (2 * np.std(klist_np))]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 2019-04-11
      • 2023-04-11
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      相关资源
      最近更新 更多