繁体   English   中英

重新排序numpy ndarray的最后一个维度

[英]Reordering last dimension of a numpy ndarray

我有一个未指定维度的数组(可能是1D,2D,3D,4D,......)。 我想申请使用与最后一个维度相同大小的索引数组对最后一个维度进行重新排序。 我知道如何使用虚拟if ... 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!!!')

我当然不满足于此,因为它不能概括为任何维度。 如果有人能告诉我正确的方法,我将非常感激!

谢谢!

只需使用ellipsis运算符进行通用的n-dim索引 -

a[...,index]

索引到数组时有关ellipsis更多信息

ellipsis广泛问答

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM