有效地改变numpy数组的顺序

Glo*_*tas 2 python numpy

我有一个 3 维 numpy 数组。维度最大可达 128 x 64 x 8192。我想做的是通过成对交换来更改第一个维度的顺序。

到目前为止,我唯一的想法是按正确的顺序创建索引列表。

order    = [1,0,3,2...127,126]
data_new = data[order]
Run Code Online (Sandbox Code Playgroud)

我担心这不是很有效,但到目前为止我没有更好的想法

Div*_*kar 5

您可以重塑将第一个轴分成两个轴,这样后一个轴就有长度2,然后沿该轴翻转数组[::-1],最后重塑回原始形状。

因此,我们会有这样的实现 -

a.reshape(-1,2,*a.shape[1:])[:,::-1].reshape(a.shape)
Run Code Online (Sandbox Code Playgroud)

样本运行 -

In [170]: a = np.random.randint(0,9,(6,3))

In [171]: order = [1,0,3,2,5,4]

In [172]: a[order]
Out[172]: 
array([[0, 8, 5],
       [4, 5, 6],
       [0, 0, 2],
       [7, 3, 8],
       [1, 6, 3],
       [2, 4, 4]])

In [173]: a.reshape(-1,2,*a.shape[1:])[:,::-1].reshape(a.shape)
Out[173]: 
array([[0, 8, 5],
       [4, 5, 6],
       [0, 0, 2],
       [7, 3, 8],
       [1, 6, 3],
       [2, 4, 4]])
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望有效地创建那些不断翻转的索引order,我们可以这样做 -

order = np.arange(data.shape[0]).reshape(-1,2)[:,::-1].ravel()
Run Code Online (Sandbox Code Playgroud)