我有一个未指定维度的数组(可能是 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!!!')
我当然对此不满意,因为它不能推广到任何维度。如果有人能向我指出正确的方法,我将不胜感激!
Thanks!
只需使用ellipsis
泛型运算符n-dim
索引-
a[...,index]
更多信息关于ellipsis当索引到数组时 https://stackoverflow.com/a/40383002/.
广泛的问答ellipsis https://stackoverflow.com/questions/772124/what-does-the-python-ellipsis-object-do.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)