左循环 numpy 数组的最快方法(如弹出、推送队列) [英] Fastest way to left-cycle a numpy array (like pop, push for a queue)
问题描述
使用 numpy 数组,我想执行此操作:
- 移动
x[1],...,x[n-1]
到x[0],...,x[n-2]
(左移), - 在最后一个索引中写入一个新值:
x[n-1] = newvalue
.
这类似于先进后出队列的pop()
, push(newvalue)
(仅反转).
一个简单的实现是:x[:-1] = x[1:];x[-1] = 新值
.
另一个使用 np.concatenate
的实现速度较慢:np.concatenate((x[1:], np.array(newvalue).reshape(1,)), axis=0)
.
有没有最快的方法?
经过一些实验,很明显:
- 需要复制,
- 对于
nparray
(numpy 数组)来说,最快和最简单的方法是切片和复制.
所以解决方案是:x[:-1] = x[1:];x[-1] = 新值
.
这是一个小基准:
<预><代码>>>>x = np.random.randint(0, 1e6, 10**8);新值 = -100>>>%timeit x[:-1] = x[1:];x[-1] = 新值1000 个循环,最好的 3 个:每个循环 73.6 毫秒>>>%timeit np.concatenate((x[1:], np.array(newvalue).reshape(1,)), axis=0)1 个循环,最好的 3 个:每个循环 339 毫秒但是如果您不需要快速访问数组中的所有值,而只需要快速访问第一个或最后一个,请使用 deque
更智能.
With numpy arrays, I want to perform this operation:
- move
x[1],...,x[n-1]
tox[0],...,x[n-2]
(left shift), - write a new value in the last index:
x[n-1] = newvalue
.
This is similar to a pop()
, push(newvalue)
for a first-in last-out queue (only inverted).
A naive implementation is: x[:-1] = x[1:]; x[-1] = newvalue
.
Another implementation, using np.concatenate
, is slower: np.concatenate((x[1:], np.array(newvalue).reshape(1,)), axis=0)
.
Is there a fastest way to do it?
After some experiments, it is clear that:
- copying is required,
- and the fastest and simplest way to do that, for
nparray
(numpy arrays) is a slicing and copying.
So the solution is: x[:-1] = x[1:]; x[-1] = newvalue
.
Here is a small benchmark:
>>> x = np.random.randint(0, 1e6, 10**8); newvalue = -100
>>> %timeit x[:-1] = x[1:]; x[-1] = newvalue
1000 loops, best of 3: 73.6 ms per loop
>>> %timeit np.concatenate((x[1:], np.array(newvalue).reshape(1,)), axis=0)
1 loop, best of 3: 339 ms per loop
But if you don't need to have a fast access to all values in the array, but only the first or last ones, using a deque
is smarter.
这篇关于左循环 numpy 数组的最快方法(如弹出、推送队列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!