[英]Reordering last dimension of a numpy ndarray
I have an array of unspecified dimension (it may be 1D, 2D, 3D, 4D, ...). 我有一个未指定维度的数组(可能是1D,2D,3D,4D,......)。 I want to apply to reorder on the last dimension using an array of the index of the same size as the last dimension.
我想申请使用与最后一个维度相同大小的索引数组对最后一个维度进行重新排序。 I know how to do it with a dummy if ... if statement:
我知道如何使用虚拟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!!!')
I am of course not satisfied with this because it cannot be generalized to any dimension. 我当然不满足于此,因为它不能概括为任何维度。 I would be very grateful if someone could indicate to me the correct way to do it!
如果有人能告诉我正确的方法,我将非常感激!
Thanks! 谢谢!
Simply use the ellipsis
operator for a generic n-dim
indexing - 只需使用
ellipsis
运算符进行通用的n-dim
索引 -
a[...,index]
More info on ellipsis
when indexing into arrays . 索引到数组时有关
ellipsis
更多信息 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.