我有一个应用程序,我需要根据一些步幅沿着NumPy数组的一个轴反转元素。举个例子,让我们考虑一下我有以下数组
In [1]: import numpy as np
In [2]: a = np.array([[1,2],[3,4],[5,6],[7,8]])
In [3]: a
Out[3]:
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
我希望沿着第一个轴(axis=0
)以2的步幅反转此数组。换句话说,我想快速获得以下数组:
Out[4]:
array([[3, 4],
[1, 2],
[7, 8],
[5, 6]])
使用内置的NumPy例程有快速的方法吗?
答案 0 :(得分:4)
Reshape to a 3d array; reverse one dimension; return to 2d:
In [51]: a = np.array([[1,2],[3,4],[5,6],[7,8]])
In [52]: a
Out[52]:
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
In [53]: a.reshape(2,2,2)
Out[53]:
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
In [54]: a.reshape(2,2,2)[:,::-1,:]
Out[54]:
array([[[3, 4],
[1, 2]],
[[7, 8],
[5, 6]]])
In [55]: a.reshape(2,2,2)[:,::-1,:].reshape(4,2)
Out[55]:
array([[3, 4],
[1, 2],
[7, 8],
[5, 6]])