是否有内置的Numpy / Scipy函数来查找四分位数范围?我自己可以很容易地做到这一点,但是mean()
基本上存在sum/len
...
def IQR(dist):
return np.percentile(dist, 75) - np.percentile(dist, 25)
Answers:
np.percentile
接受多个百分位参数,这样做会稍微好一些:
q75, q25 = np.percentile(x, [75 ,25])
iqr = q75 - q25
要么
iqr = np.subtract(*np.percentile(x, [75, 25]))
而不是两次致电percentile
:
In [8]: x = np.random.rand(1e6)
In [9]: %timeit q75, q25 = np.percentile(x, [75 ,25]); iqr = q75 - q25
10 loops, best of 3: 24.2 ms per loop
In [10]: %timeit iqr = np.subtract(*np.percentile(x, [75, 25]))
10 loops, best of 3: 24.2 ms per loop
In [11]: %timeit iqr = np.percentile(x, 75) - np.percentile(x, 25)
10 loops, best of 3: 33.7 ms per loop
np.substract.reduce
。恕我直言,比*魔法还清晰一些。
如果Jaime的答案适合您的情况,请忽略此操作。但是,如果没有,根据此答案,要找到第一个四分位数和第三个四分位数的确切值,则应考虑执行以下操作:
samples = sorted([28, 12, 8, 27, 16, 31, 14, 13, 19, 1, 1, 22, 13])
def find_median(sorted_list):
indices = []
list_size = len(sorted_list)
median = 0
if list_size % 2 == 0:
indices.append(int(list_size / 2) - 1) # -1 because index starts from 0
indices.append(int(list_size / 2))
median = (sorted_list[indices[0]] + sorted_list[indices[1]]) / 2
pass
else:
indices.append(int(list_size / 2))
median = sorted_list[indices[0]]
pass
return median, indices
pass
median, median_indices = find_median(samples)
Q1, Q1_indices = find_median(samples[:median_indices[0]])
Q2, Q2_indices = find_median(samples[median_indices[-1] + 1:])
IQR = Q3 - Q1
quartiles = [Q1, median, Q2]
代码来自引用的答案。