三维numpy数组按照二维索引排序

2024-04-19 12:09:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的有麻烦了。我有一个三维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]]]
)

希望这是清楚的,如果不是请询问。提前谢谢!你知道吗


Tags: innumpyfor排序编程np情况数组
2条回答

所以,这些线索已经在这里有用的注释中了,但是为了完整性,它只需要使用np.沿\u轴取\u以及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)

这样做的好处是,如果三维阵列的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]]])

如果您希望得到一个ph.shape形状的数组,您可以简单地np.squeezeph_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]])

相关问题 更多 >