我有一个1D numpy数组
x=np.array([0.1,0.3,0.2,0.4,0.5,0.4])
我需要计算另一个相同大小的数组,其中每个元素都是排序数组中的ID(或称为索引(。这里排序的数组是[0.1,0.2,0.3,0.4,0.5]。因此,0.1对应于ID 0;0.2对应ID 1;。。。0.5对应于ID 4。预期结果将是
[0,2,1,3,4,3]
注意,这个问题与Python中如何获得原始列表的排序列表的索引类似,但不同?因为我们需要处理重复的元素。
您可以使用np.unique
:
uniques, out = np.unique(x, return_inverse=True)
输出(out
(:
array([0, 2, 1, 3, 4, 3])
也就是说,通常应该避免使用独特的浮动。
尝试:np.searchsorted
:
>>> x = np.array([0.1,0.3,0.2,0.4,0.5,0.4])
>>> np.searchsorted(np.unique(x), x)
array([0, 2, 1, 3, 4, 3], dtype=int32)
np.unique
按排序顺序输出唯一项目。
只需使用
import numpy as np
x=np.array([0.1,0.3,0.2,0.4,0.5,0.4])
>>> indeces=np.argsort(x)
>>> indeces
array([0, 2, 1, 3, 5, 4])