I have a 2D numpy array and I want to create a new 1D array where it is indices of numbers in the first array if they are sorted in an ascending order. For the following array:
我有一个2D numpy数组,我想创建一个新的1D数组,如果它们按升序排序,它是第一个数组中的数字索引。对于以下数组:
A = [[1,0,2],
[0,3,0]]
I want this to be like:
我想要这样:
B = [[1,1],[0,2],[0,0],[0,1],[1,0],[1,2]]
Any idea how it can be done in python using predefined functions?
知道如何使用预定义函数在python中完成它吗?
Thanks
1 个解决方案
#1
7
You can use argsort
to sort the indices of flattened array, followed by unravel_index
to convert the flat index back to coordinates:
您可以使用argsort对flattened数组的索引进行排序,然后使用unravel_index将flat index转换回坐标:
>>> i = (-a).argsort(axis=None, kind='mergesort')
>>> j = np.unravel_index(i, a.shape)
>>> np.vstack(j).T
array([[1, 1],
[0, 2],
[0, 0],
[0, 1],
[1, 0],
[1, 2]])
-a
and kind='mergesort'
is in order to sort the array in a stable manner in descending order (to match the output you are looking for).
-a和kind ='mergesort'是为了按降序顺序对数组进行排序(以匹配您要查找的输出)。
If you do not care about having a stable sort, replace the first line with:
如果您不关心稳定排序,请将第一行替换为:
>>> i = a.argsort(axis=None)[::-1]
#1
7
You can use argsort
to sort the indices of flattened array, followed by unravel_index
to convert the flat index back to coordinates:
您可以使用argsort对flattened数组的索引进行排序,然后使用unravel_index将flat index转换回坐标:
>>> i = (-a).argsort(axis=None, kind='mergesort')
>>> j = np.unravel_index(i, a.shape)
>>> np.vstack(j).T
array([[1, 1],
[0, 2],
[0, 0],
[0, 1],
[1, 0],
[1, 2]])
-a
and kind='mergesort'
is in order to sort the array in a stable manner in descending order (to match the output you are looking for).
-a和kind ='mergesort'是为了按降序顺序对数组进行排序(以匹配您要查找的输出)。
If you do not care about having a stable sort, replace the first line with:
如果您不关心稳定排序,请将第一行替换为:
>>> i = a.argsort(axis=None)[::-1]