简体   繁体   English

重新排序ndarray的第n维

[英]Reordering the nth dimension of a ndarray

I want to reorder the nth axis of a ndarray of abitrary dimension d according to a list of indices order .我想根据索引order列表对任意维度d的 ndarray 的第 n轴进行重新排序。 If the axis was the last one, the solution from this question ( Reordering last dimension of a numpy ndarray ) would be enough.如果轴是最后一个,那么这个问题的解决方案( 重新排序 numpy ndarray 的最后一个维度)就足够了。 In my case, however, the axis is not, in general, the first or the last one, so that Ellipsis alone does not solve the issue.然而,就我而言,轴通常不是第一个或最后一个,因此 Ellipsis 本身并不能解决问题。

This is the solution I have come up so far:这是我到目前为止提出的解决方案:

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

What I don't like about this solution is that I have to manually transpose the ndarray.我不喜欢这个解决方案是我必须手动转置 ndarray。 I was wondering if there is a generalization of the Ellipsis operator such that we can account for a chosen number of axes, such that我想知道是否存在 Ellipsis 运算符的泛化,以便我们可以考虑选定数量的轴,这样

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

would skip the n first axes and would reorder the (n+1)th one.将跳过第n个轴并重新排序第(n+1) 个轴。

Is such a thing possible?这样的事情可能吗?

Use the command np.take_along_axis and assign the output to a new variable.使用命令np.take_along_axis并将 output 分配给新变量。 See the code below:请看下面的代码:

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's comment is also a valid answer (and likely better, please give them an upvote:): @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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM