问题描述
我正在尝试获取索引以按最后一个轴对多维数组进行排序,例如
>>>a = np.array([[3,1,2],[8,9,2]])我想要索引 i
使得,
基于 numpy.argsort 的文档我认为它应该这样做,但我收到错误:
>>>a[np.argsort(a)]索引错误:索引 2 超出轴 0 的范围,大小为 2我需要以相同的方式重新排列其他相同形状的数组(例如数组 b
使得 a.shape == b.shape
)...所以
以上答案现在有点过时了,因为 numpy 1.15 中添加了新功能以使其更简单;take_along_axis (https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.take_along_axis.html) 允许你做:
>>>a = np.array([[3,1,2],[8,9,2]])>>>np.take_along_axis(a, a.argsort(axis=-1),axis=-1)数组([[1 2 3][2 8 9]])I'm trying to get the indices to sort a multidimensional array by the last axis, e.g.
>>> a = np.array([[3,1,2],[8,9,2]])
And I'd like indices i
such that,
>>> a[i]
array([[1, 2, 3],
[2, 8, 9]])
Based on the documentation of numpy.argsort I thought it should do this, but I'm getting the error:
>>> a[np.argsort(a)]
IndexError: index 2 is out of bounds for axis 0 with size 2
Edit: I need to rearrange other arrays of the same shape (e.g. an array b
such that a.shape == b.shape
) in the same way... so that
>>> b = np.array([[0,5,4],[3,9,1]])
>>> b[i]
array([[5,4,0],
[9,3,1]])
The above answers are now a bit outdated, since new functionality was added in numpy 1.15 to make it simpler; take_along_axis (https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.take_along_axis.html) allows you to do:
>>> a = np.array([[3,1,2],[8,9,2]])
>>> np.take_along_axis(a, a.argsort(axis=-1), axis=-1)
array([[1 2 3]
[2 8 9]])
这篇关于用于多维 ndarray 的 argsort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!