首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >你如何在Numpy中找到IQR?

你如何在Numpy中找到IQR?
EN

Stack Overflow用户
提问于 2014-04-23 03:12:43
回答 3查看 75.2K关注 0票数 84

有没有内置的Numpy/Scipy函数来找出四分位数的范围?我自己可以很容易地做到这一点,但是mean()确实存在,它基本上就是sum/len

代码语言:javascript
复制
def IQR(dist):
    return np.percentile(dist, 75) - np.percentile(dist, 25)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-04-23 04:10:27

np.percentile接受多个百分位数的参数,您最好执行以下操作:

代码语言:javascript
复制
q75, q25 = np.percentile(x, [75 ,25])
iqr = q75 - q25

代码语言:javascript
复制
iqr = np.subtract(*np.percentile(x, [75, 25]))

而不是向percentile发出两个调用

代码语言:javascript
复制
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
票数 126
EN

Stack Overflow用户

发布于 2016-07-28 02:01:57

现在scipy.stats中有一个iqr函数。它从scipy 0.18.0开始可用。我的初衷是将其添加到numpy中,但它被认为过于特定于领域。

您可能会更好地使用Jaime的答案,因为scipy代码只是一个过于复杂的版本。

票数 27
EN

Stack Overflow用户

发布于 2020-02-13 21:53:46

如果Jaime's answer适用于您的情况,请忽略此选项。但如果不是这样,根据this answer的说法,要找到第一个和第三个四分位数的精确值,你应该考虑这样做:

代码语言:javascript
复制
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]

取自引用答案的代码。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23228244

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档