对分箱数据使用 numpy 百分位数

xnx*_*xnx 5 python numpy

假设一个城镇的房屋销售数据的范围如下:

< $100,000              204
$100,000 - $199,999    1651
$200,000 - $299,999    2405
$300,000 - $399,999    1972
$400,000 - $500,000     872
> $500,000             1455
Run Code Online (Sandbox Code Playgroud)

我想知道给定的百分位数属于哪个房价区间。有没有办法使用 numpy 的percentile函数来做到这一点?我可以用手做:

import numpy as np
a = np.array([204., 1651., 2405., 1972., 872., 1455.])
b = np.cumsum(a)/np.sum(a) * 100
q = 75
len(b[b <= q])
4       # ie bin $300,000 - $399,999
Run Code Online (Sandbox Code Playgroud)

但有没有办法可以替代np.percentile呢?

per*_*iae 2

你就快到了:

\n\n
cs = np.cumsum(a)\nbin_idx = np.searchsorted(cs, np.percentile(cs, 75))\n
Run Code Online (Sandbox Code Playgroud)\n\n

至少对于这种情况(以及其他一些具有更大a数组的情况),它并没有更快:

\n\n
In [9]: %%timeit\n   ...: b = np.cumsum(a)/np.sum(a) * 100\n   ...: len(b[b <= 75])\n   ...:\n10000 loops, best of 3: 38.6 \xc2\xb5s per loop\n\nIn [10]: %%timeit\n   ....: cs = np.cumsum(a)\n   ....: np.searchsorted(cs, np.percentile(cs, 75))\n   ....:\n10000 loops, best of 3: 125 \xc2\xb5s per loop\n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,除非您想检查多个百分位数,否则我会坚持使用您所拥有的。

\n