python - 如何旋转形状为 (n,) 或 (n,1) 的 numpy 数组中的数字?

标签 python numpy

假设我有一个 numpy 数组:

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

我想“旋转”它以获得:

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

什么是最好的方法?

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

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

最佳答案

只需使用 numpy.roll功能:

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

另见 this question .

关于python - 如何旋转形状为 (n,) 或 (n,1) 的 numpy 数组中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15969708/

相关文章:

python - numpy 二维数组 : get indices of all entries that are connected and share the same value

python - 多维索引切片后数组的维度

python - 为什么网络摄像机无法以python代码读取视频供稿?

python - 如何将python中的元素按n个元素分组

python - 将python中列表的字符串表示形式转换为列表对象

python - 重新采样表示图像的 numpy 数组

python - 如何用numpy计算二维向量和OX之间的角度?

python - 为什么具有 100 亿次迭代的大型 for 循环在 Python 中的运行时间比在 C 中的运行时间长得多?

python - 将每个 var 输入写入文本文件中的新行

python - 没有名为 numpy 的模块