简体   繁体   English

如何在numpy数组形状(n,)或(n,1)中旋转数字?

[英]How do you rotate the numbers in an numpy array of shape (n,) or (n,1)?

Say I have a numpy array: 说我有一个numpy数组:

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

and I want to "rotate" it to get: 我想“旋转”它得到:

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

What is the best way? 什么是最好的方法?

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)

Just use the numpy.roll function: 只需使用numpy.roll函数:

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

See also this question . 另见这个问题

numpy.concatenate([a[-1:], a[:-1]])
>>> array([4, 0, 1, 2, 3])

试试这个吧

b = a[-1:]+a[:-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何用'n'单位旋转2D numpy数组中的元素? - How do you rotate elements in a 2D numpy array by 'n' units? 如何展平(n,)形状numpy数组 - how to flatten (n, ) shape numpy array 如何将一系列形状为 (n,1) 的数字作为 n 个唯一数字的数组重复 4 次,形状为 (n,1) - How to repeat a series of numbers with shape (n,1) as an array of n unique numbers repeated by 4 times with a shape of (n,1) 将形状数组(n,)转换为numpy形状数组(n,1) - Transform an array of shape (n,) to a numpy array of shape (n,1) 将 Numpy 数组重塑为形状为 (n, n, n) 的立方体的字典列表 - Reshaping a Numpy Array into lexicographical list of cubes of shape (n, n, n) 如何在形状为 (n,m) 的 numpy 数组的选定列中添加元素? - How to add element in a selected column of a numpy array of shape (n,m)? (n,) 对于 numpy 数组形状意味着什么? - What does (n,) mean for a numpy array shape? 如何使用形状为 (N,) 的一维数组索引 N 维 numpy 数组 - How to index a numpy array of dimension N with a 1-dimensional array of shape (N,) 如何将 pandas dataframe 列转换为图像数组,即 Python 中形状为 (n,n) 的 numpy 数组? - How to convert a pandas dataframe column to an image array i.e. a numpy array with shape (n,n) in Python? 如何将形状 n 的数组转换为 n,m - How to covert array of shape n, to n,m
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM