重新排列数据数组的第n维

2024-06-10 16:32:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据索引列表对任意维d数据列的n轴重新排序顺序。如果轴是最后一个轴,那么这个问题(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。我想知道是否有一个省略算子的推广,这样我们就可以解释一个选定数量的轴,这样

ndarr[GenEllipsis(n),order,...]

将跳过n第一个轴,并将(n+1)第个轴重新排序

这可能吗


Tags: the数据列表排序顺序nporder解决方案
1条回答
网友
1楼 · 发布于 2024-06-10 16:32:23

使用命令np.take_along_axis并将输出分配给新变量。请参阅下面的代码:

arr = np.random.randn(10,3,23,42,3)
ax = 3 #change this to your 'random' axis
order = np.random.permutation(list(range(arr.shape[ax])))
#order needs to have the same number of dims as arr
order = np.expand_dims(order,tuple(i for i in range(len(arr.shape)) if i != ax)) 
shuff_arr = np.take_along_axis(arr,order,ax)

@hpaulj的评论也是一个有效的答案(而且可能更好,请给他们一个投票权!)

arr = np.random.randn(10,3,23,42,3)
ax = 3 #change this to your 'random' axis
order = np.random.permutation(list(range(arr.shape[ax])))
#set the correct dim to 'order'
alist = [slice(None)]*len(arr.shape)
alist[ax] = order
shuff_arr = arr[tuple(alist)]

相关问题 更多 >