gpt4 book ai didi

python-3.x - 沿轴交换一对元素

转载 作者:行者123 更新时间:2023-12-05 03:58:07 27 4
gpt4 key购买 nike

我有一个 2d 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”解决方案有什么想法吗?

最佳答案

由于第一对不完全订阅通常的对交换,我们可以单独进行。对于其余部分,它会相对直接地重新整形以拆分轴和翻转轴。因此,这将是 -

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]])

关于python-3.x - 沿轴交换一对元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58172442/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com