如何将浮点数数组转换为唯一整数数组?

时间:2019-08-31 20:59:47

标签: python-3.x

我有一个浮点数组,我想将其转换为整数数组,以使整数数组包含与np.arange(array_of_floats)相同的元素。我希望对整数数组进行排序,以反映浮点数数组中元素的相对大小。

例如,如果浮点数数组中索引为5的元素是第三小的元素,则索引数为5的整数数组中的元素应为2。

如果float数组中索引为3的元素最小,则索引为3的整数数组中的元素应为0。

举一些例子:

floats = [1.2, 3.4, 2.1, 0.4]
# I want to generate the following array:
integers = [1, 3, 2, 0]

另一个例子:

floats = [5.4, 2.3, 6.2, 1.2, 7.4, 3.2]
integers = [3, 1, 4, 0, 5, 2]

1 个答案:

答案 0 :(得分:1)

您可以对花车列表进行排序,并将已排序列表中的花车映射到原始列表中的索引:

floats = [1.2, 3.4, 2.1, 0.4]

sorted_floats = sorted(floats)

integers = list(map(sorted_floats.index, floats))

print(integers)

输出:

[1, 3, 2, 0]
相关问题