簡體   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