【发布时间】:2021-05-20 12:14:41
【问题描述】:
我想根据索引列表 order 对任意维度 d 的 ndarray 的 nth 轴重新排序。如果轴是最后一个,那么这个问题(Reordering last dimension of a numpy ndarray)的解决方案就足够了。然而,就我而言,轴通常不是第一个或最后一个,因此仅靠省略号并不能解决问题。
这是我迄今为止提出的解决方案:
axes_list = list(range(d))
axes_list[0], axes_list[i] = axes_list[i], axes_list[0]
ndarr = np.transpose(ndarr, axes=axes_list)[order,...] # Switches the axis with the first and reorders
ndarr = np.transpose(ndarr, axes=axes_list) # Switches the axes back
我不喜欢这个解决方案是我必须手动转置 ndarray。我想知道是否存在 Ellipsis 运算符的泛化,以便我们可以考虑选定数量的轴,这样
ndarr[GenEllipsis(n),order,...]
将跳过第 n 个轴并重新排列第 (n+1) 个 个轴。
这样的事情可能吗?
【问题讨论】:
-
使用
n":"。更一般地说,您可以创建一个alist = [[slice(None)]*d;用订单替换一个或多个切片。最后索引tupe(alist)。这种方法很通用。 -
我不确定我是否理解,您能详细说明一下吗?去 `arr[:,:,:(n times),:,:]` 是不行的,因为我在写代码的时候要指定维数,而且我事先不知道(维数尺寸是任意的)。
标签: python numpy numpy-ndarray