排序N-D numpy的阵列由另一个一维阵列 [英] Sort N-D numpy array by another 1-D array

查看:138
本文介绍了排序N-D numpy的阵列由另一个一维阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这个问题的答案(<一个href=\"http://stackoverflow.com/questions/6162172/sort-a-numpy-array-by-another-array-along-a-particular-axis-using-less-memory\">Sort另一个数组numpy的阵列,沿特定轴线,使用较少的内存),我学会了如何排序多维数组numpy的 A 另一个numpy的值阵列 b 不会造成太多额外的数组。

From the answer to this question (Sort a numpy array by another array, along a particular axis, using less memory), I learned how to sort a multidimensional numpy array a by the values of another numpy array b without creating too many additional arrays.

然而, numpy.rec.fromarrays([A,B])只能当阵列 A b 具有相同的形状。我的 B 数组是一维数组,但 A 阵列是N-D阵列(没有指定n)。它是一个很好的方式(高效)来排序特定轴线之间的阵列由一维数组的值 B

However, numpy.rec.fromarrays([a, b]) only works if the arrays a and b have the same shape. My b array is 1-D array, but a array is a N-D array (N is not specified). Is it a nice way (and efficient) to sort the a array among a particular axis by the value of the 1-D array b?

推荐答案

使用 np.take 关键字参数:

>>> a = np.arange(2*3*4).reshape(2, 3, 4)
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> b = np.arange(3)
>>> np.random.shuffle(b)
>>> b
array([1, 0, 2])
>>> np.take(a, b, axis=1)
array([[[ 4,  5,  6,  7],
        [ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],

       [[16, 17, 18, 19],
        [12, 13, 14, 15],
        [20, 21, 22, 23]]])

如果你想使用花哨的索引,你只需要垫有足够的空片索引元组:

If you want to use fancy indexing, you just need to pad the indexing tuple with enough empty slices:

>>> a[:, b]
array([[[ 4,  5,  6,  7],
        [ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],

       [[16, 17, 18, 19],
        [12, 13, 14, 15],
        [20, 21, 22, 23]]])

或者在更一般的设置:

Or in a more general setting:

>>> axis = 1
>>> idx = (slice(None),) * axis + (b,)
>>> a[idx]
array([[[ 4,  5,  6,  7],
        [ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],

       [[16, 17, 18, 19],
        [12, 13, 14, 15],
        [20, 21, 22, 23]]])

np.take 真的应该是您的第一选择。

But np.take should really be your first option.

这篇关于排序N-D numpy的阵列由另一个一维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆