如何旋转形状为(n,)或(n,1)的numpy数组中的数字? [英] How do you rotate the numbers in an numpy array of shape (n,) or (n,1)?

查看:110
本文介绍了如何旋转形状为(n,)或(n,1)的numpy数组中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个numpy数组:

Say I have a numpy array:

>>> a 
array([0,1,2,3,4])

我想对其进行旋转"以获得:

and I want to "rotate" it to get:

>>> b
array([4,0,1,2,3])

最好的方法是什么?

我一直在转换成双端队列(见下文),但是有更好的方法吗?

I have been converting to a deque and back (see below) but is there a better way?

b = deque(a)
b.rotate(1)
b = np.array(b)

推荐答案

只需使用 numpy.roll 函数:

Just use the numpy.roll function:

a = np.array([0,1,2,3,4])
b = np.roll(a,1)
print(b)
>>> [4 0 1 2 3]

另请参见此问题.

这篇关于如何旋转形状为(n,)或(n,1)的numpy数组中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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