重新排序数组的最后一个维度

2024-04-25 04:33:39 发布

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

我有一个未指定维度的数组(可能是1D,2D,3D,4D,…)。我想使用与最后一个维度大小相同的索引数组对最后一个维度进行重新排序。我知道怎么处理一个假人如果。。。if语句:

import numpy as np

a = np.ones((10, 10, 20, 40,30,10))
index=np.arange(a.shape[-1])

if len(a.shape)==1:
    a=a[index]
elif len(a.shape)==2:
    a=a[:,index]
elif len(a.shape)==3:
    a=a[:,:,index]
elif len(a.shape)==4:
    a=a[:,:,:,index]
elif  len(a.shape)==5:
    a=a[:,:,:,:,index]
else:
    print('Dimensions too high!!!')

我当然不满意这一点,因为它不能推广到任何维度。如果有人能告诉我正确的方法,我将非常感激!你知道吗

谢谢!你知道吗


Tags: importnumpyindexlenif排序asnp