左循环numpy数组的最快方法(例如pop,push for queue) [英] Fastest way to left-cycle a numpy array (like pop, push for a queue)

查看:266
本文介绍了左循环numpy数组的最快方法(例如pop,push for queue)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于numpy数组,我要执行此操作:

With numpy arrays, I want to perform this operation:

  • x[1],...,x[n-1]移至x[0],...,x[n-2](左移),
  • 在最后一个索引中写一个新值:x[n-1] = newvalue.
  • move x[1],...,x[n-1] to x[0],...,x[n-2] (left shift),
  • write a new value in the last index: x[n-1] = newvalue.

这类似于先进先出队列(仅倒排)的pop()push(newvalue).

This is similar to a pop(), push(newvalue) for a first-in last-out queue (only inverted).

一个简单的实现是:x[:-1] = x[1:]; x[-1] = newvalue.

使用np.concatenate的另一种实现较慢:np.concatenate((x[1:], np.array(newvalue).reshape(1,)), axis=0).

Another implementation, using np.concatenate, is slower: np.concatenate((x[1:], np.array(newvalue).reshape(1,)), axis=0).

有最快的方法吗?

推荐答案

经过一些实验,很明显:

After some experiments, it is clear that:

  • 需要复制
  • 也是最快最简单的方法,对于nparray(numpy数组)是切片和复制.
  • copying is required,
  • and the fastest and simplest way to do that, for nparray (numpy arrays) is a slicing and copying.

因此解决方案是:x[:-1] = x[1:]; x[-1] = newvalue.

这是一个小基准:

>>> 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数组的最快方法(例如pop,push for queue)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆