我有一个列表,其中包含随机数量的整数和/或浮点数。我的目标是找出我的数字中的异常(希望使用正确的词语来解释这一点)。例如:
list = [1, 3, 2, 14, 108, 2, 1, 8, 97, 1, 4, 3, 5]
- 我的整数值中,90到99%的值都在1到20之间。
- 有时会出现远高于此范围的值,比如100或1,000甚至更多。
我的问题是这些值每次都可能不同。也许正常范围在1,000到1,200之间,而异常值则在50万左右。
是否有函数可以过滤掉这些特殊的数字?
我有一个列表,其中包含随机数量的整数和/或浮点数。我的目标是找出我的数字中的异常(希望使用正确的词语来解释这一点)。例如:
list = [1, 3, 2, 14, 108, 2, 1, 8, 97, 1, 4, 3, 5]
我的问题是这些值每次都可能不同。也许正常范围在1,000到1,200之间,而异常值则在50万左右。
是否有函数可以过滤掉这些特殊的数字?
假设你的列表是l
:
If you know you want to filter a certain percentile/quantile, you can use:
This removes bottom 10% and top 90%. Of course, you can change any of them to your desired cut-off (for example you can remove the bottom filter and only filter the top 90% in your example):
import numpy as np
l = np.array(l)
l = l[(l>np.quantile(l,0.1)) & (l<np.quantile(l,0.9))].tolist()
output:
[ 3 2 14 2 8 4 3 5]
If you are not sure of the percentile cut-off and are looking to remove outliers:
You can adjust your cut-off for outliers by adjusting argument m
in
function call. The larger it is, the less outliers are removed. This function seems to be more robust to various types of outliers compared to other outlier removal techniques.
import numpy as np
l = np.array(l)
def reject_outliers(data, m=6.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d / (mdev if mdev else 1.)
return data[s < m].tolist()
print(reject_outliers(l))
output:
[1, 3, 2, 14, 2, 1, 8, 1, 4, 3, 5]
filter()
方法:lst1 = [1, 3, 2, 14, 108, 2, 1, 8, 97, 1, 4, 3, 5]
lst2 = list(filter(lambda x: x > 5,lst1))
print(lst2)
输出:
[14, 108, 8, 97]
5
或任何其他值。 - DeepSpace所以这里有一个方法,可以阻止那些偏离主题的人
import math
_list = [1, 3, 2, 14, 108, 2, 1, 8, 97, 1, 4, 3, 5]
def consts(_list):
mu = 0
for i in _list:
mu += i
mu = mu/len(_list)
sigma = 0
for i in _list:
sigma += math.pow(i-mu,2)
sigma = math.sqrt(sigma/len(_list))
return sigma, mu
def frequence(x, sigma, mu):
return (1/(sigma*math.sqrt(2*math.pi)))*math.exp(-(1/2)*math.pow(((x-mu)/sigma),2))
sigma, mu = consts(_list)
new_list = []
for i in range(len(_list)):
if frequence(_list[i], sigma, mu) > 0.01:
new_list.append(i)
print(new_list)
20
或任何其他值。此外,在迭代时删除列表中的元素永远不是一个好主意(即使您发布的代码也会导致IndexError
)。 - DeepSpace