沿轴交换一对元素

时间:2019-09-30 17:15:43

标签: python-3.x numpy

我有一个二维的numpy数组,例如:

import numpy as np

a = np.arange(20).reshape((2,10))

# array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
#   [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

我想交换每一行中的元素对。所需的输出如下所示:

# array([[ 9, 0, 2,  1,  4,  3,  6,  5,  8,  7],
#   [19, 10, 12, 11, 14, 13, 16, 15, 18, 17]])

我设法在1d内找到解决方案:

a = np.arange(10)

# does the job for all pairs except the first
output = np.roll(np.flip(np.roll(a,-1).reshape((-1,2)),1).flatten(),2)

# first pair done manually
output[0] = a[-1]
output[1] = a[0]

关于2d情况的“仅numpy”解决方案的任何想法吗?

1 个答案:

答案 0 :(得分:2)

由于第一对没有完全订阅通常的对交换,因此我们可以分开进行。对于其余部分,通过重整形状以拆分轴和翻转轴将相对简单。因此,它将是-

In [42]: a # 2D input array
Out[42]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

In [43]: b2 = a[:,1:-1].reshape(a.shape[0],-1,2)[...,::-1].reshape(a.shape[0],-1)

In [44]: np.hstack((a[:,[-1,0]],b2))
Out[44]: 
array([[ 9,  0,  2,  1,  4,  3,  6,  5,  8,  7],
       [19, 10, 12, 11, 14, 13, 16, 15, 18, 17]])

或者,堆叠然后reshape + flip-axis-

In [50]: a1 = np.hstack((a[:,[0,-1]],a[:,1:-1]))

In [51]: a1.reshape(a.shape[0],-1,2)[...,::-1].reshape(a.shape[0],-1)
Out[51]: 
array([[ 9,  0,  2,  1,  4,  3,  6,  5,  8,  7],
       [19, 10, 12, 11, 14, 13, 16, 15, 18, 17]])