1

我在这方面遇到了真正的麻烦。我有一个三维 numpy 数组,我想通过二维索引数组对其进行重新排序。实际上,数组将以编程方式确定,并且三维数组可能是二维或四维的,但为了简单起见,如果两个数组都是二维的,则以下是所需的结果:

ph = np.array([[1,2,3], [3,2,1]])
ph_idx = np.array([[0,1,2], [2,1,0]])
for sub_dim_n, sub_dim_ph_idx in enumerate(ph_idx):
    ph[sub_dim_n] = ph[sub_dim_n][sub_dim_ph_idx]

这使得 ph 数组变为:

array([[1, 2, 3],
       [1, 2, 3]])

这就是我想要的。如果情况相同,任何人都可以帮忙,但是我有一个三维数组(psh)而不是 ph,例如:

psh = np.array(
    [[[1,2,3]], 
     [[3,2,1]]]
)

希望这很清楚,如果不是,请询问。提前致谢!

4

2 回答 2

2

如果您想要最终得到一个ph.shape形状数组,您可以简单地np.squeeze ph_ixs使形状匹配,并使用它来索引ph

print(ph)
[[[1 2 3]]
 [[3 2 1]]]

print(ph_idx)
[[0 1 2]
 [2 1 0]]

np.take_along_axis(np.squeeze(ph), ph_idx, axis=-1)

array([[1, 2, 3],
       [1, 2, 3]])
于 2019-11-04T09:21:12.523 回答
0

因此,线索已经在此处的有用评论中,但为了完整起见,它就像使用 np.take_along_axis 和 2d 数组的广播版本一样简单:

psh = np.array(
    [[[1,2,3]], 
     [[3,2,1]]]
)
ph_idx = np.array(
    [[0,1,2], 
     [2,1,0]]
)
np.take_along_axis(psh, ph_idx[:, None, :], axis=2)

如果 3d 数组的 dim1 具有多个元素,这也具有以下优点:

psh = np.array(
    [[[1,2,3],[4,5,6],[7,8,9]], 
     [[3,2,1],[6,5,4],[9,8,7]]]
)
ph_idx = np.array([[0,1,2], [2,1,0]])
np.take_along_axis(psh, ph_idx[:, None, :], axis=2)

这使

array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]])
于 2019-11-04T11:19:09.200 回答