Python:将非负整数有效地转换为0到1之间的值

时间:2019-03-03 13:30:56

标签: python performance numpy math computer-science

将整数列表转换为介于0和1之间的有效方法是什么,例如:

[0] -> [0]
[9] -> [0.9]
[9, 19] -> [0.09, 0.19]
[9, 19, 1000] -> [0.0009, 0.0019, 0.1]

我在想:

def integer_to_0_1(numpy_array):
    divisor = 10 ** len(str(np.max(numpy_array)))
    return numpy_array/divisor

原因

我正在从其他2列的熊猫数据框中创建一个ID,但是我希望该ID是可排序的。因此,我想将ID设置为"col1_col2"这样的数字,而不是像col1.col2这样的字符串来创建ID,它很容易进行排序并且不会丢失订单信息。例如

---------------              ------------
| col1 | col2 |              | ID       |
| 0    | 0    |      ->      | 0        | 
| 0    | 110  |              | 0.110    |
| 2332 | 3    |              | 2332.003 |

1 个答案:

答案 0 :(得分:0)

以下是一种将值列表映射到[0,1]的方法。 (包括0和1)

def convert(numpy_array):
    return (numpy_array- np.min(numpy_array))/(np.max(numpy_array) - np.min(numpy_array))

您可以如下映射数组[3, 4, 5, 2, 7]

[0.2 0.4 0.6 0.  1. ]