我有一个 numpy 数组,其中包含长度为 m
的严格递增“截止”值,以及一系列 pandas 值(认为索引并不重要,这可以转换为 numpy数组),长度为 n 的值。
我需要想出一种有效的方法来吐出一个长度 m
向量,该向量包含 pandas 系列中小于“cutoff”数组的第 j 个元素的元素数量。
我可以通过列表迭代器来做到这一点:
output = array([(pan_series < cutoff_val).sum() for cutoff_val in cutoff_ar])
但我想知道是否有任何方法可以利用 numpy 的神奇速度来做到这一点,因为我必须在多个循环中执行此操作多次,并且它会不断使我的计算机崩溃。
谢谢!
最佳答案
这是您要找的吗?
In [36]: a = np.random.random(20)
In [37]: a
Out[37]:
array([ 0.68574307, 0.15743428, 0.68006876, 0.63572484, 0.26279663,
0.14346269, 0.56267286, 0.47250091, 0.91168387, 0.98915746,
0.22174062, 0.11930722, 0.30848231, 0.1550406 , 0.60717858,
0.23805205, 0.57718675, 0.78075297, 0.17083826, 0.87301963])
In [38]: b = np.array((0.3,0.7))
In [39]: np.sum(a[:,None]<b[None,:], axis=0)
Out[39]: array([ 8, 16])
In [40]: np.sum(a[:,None]<b, axis=0) # b's new axis above is unnecessary...
Out[40]: array([ 8, 16])
In [41]: (a[:,None]<b).sum(axis=0) # even simpler
Out[41]: array([ 8, 16])
计时总是很受欢迎(对于较长的 2E6 元素数组)
In [47]: a = np.random.random(2000000)
In [48]: %timeit (a[:,None]<b).sum(axis=0)
10 loops, best of 3: 78.2 ms per loop
In [49]: %timeit np.searchsorted(a, b, 'right',sorter=a.argsort())
1 loop, best of 3: 448 ms per loop
对于较小的数组
In [50]: a = np.random.random(2000)
In [51]: %timeit (a[:,None]<b).sum(axis=0)
10000 loops, best of 3: 89 µs per loop
In [52]: %timeit np.searchsorted(a, b, 'right',sorter=a.argsort())
The slowest run took 4.86 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 141 µs per loop
编辑
Divakar 表示,在较长的 b
中情况可能会有所不同,让我们看看
In [71]: a = np.random.random(2000)
In [72]: b =np.random.random(200)
In [73]: %timeit (a[:,None]<b).sum(axis=0)
1000 loops, best of 3: 1.44 ms per loop
In [74]: %timeit np.searchsorted(a, b, 'right',sorter=a.argsort())
10000 loops, best of 3: 172 µs per loop
确实很不一样!感谢您激发了我的好奇心。
OP可能应该测试他的用例,是否涉及截止序列的非常长的样本?哪里有平衡?
编辑 #2
我的计时出了问题,我忘记了 .sum()
的 axis=0
参数...
我已经用更正的语句编辑了时间安排,当然还有更正的时间安排。抱歉。
关于python - python中数组元素的数量小于截止数组的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36318618/