Python截断切片分配(Python truncating slice assignment)

我想知道为什么每当我将浮点数分配给一个numpy数组时Python都会将数字截断为整数:

import numpy as np lst = np.asarray(list(range(10))) print ("lst before assignment: ", lst) lst[:4] = [0.3, 0.5, 10.6, 0.2]; print ("lst after assignment: ", lst)

输出:

lst before assignment: [0 1 2 3 4 5 6 7 8 9] lst after assignment: [ 0 0 10 0 4 5 6 7 8 9]

为什么这样做? 既然你不需要在语言中指定类型,我不明白为什么numpy会在赋值给数组(包含整数)之前将float s转换为int s。

I am wondering why Python truncates the numbers to integers whenever I assign floating point numbers to a numpy array:

import numpy as np lst = np.asarray(list(range(10))) print ("lst before assignment: ", lst) lst[:4] = [0.3, 0.5, 10.6, 0.2]; print ("lst after assignment: ", lst)

output:

lst before assignment: [0 1 2 3 4 5 6 7 8 9] lst after assignment: [ 0 0 10 0 4 5 6 7 8 9]

Why does it do this? Since you do not need to specify types in the language, I cannot understand why numpy would cast the floats to ints before assigning to the array (which contains integers).

最满意答案

一旦看到numpy.asarray的签名,答案很清楚:

numpy.asarray(a, dtype=None, order=None)

如果未设置dtype ,则会根据提供的数据推断。 在你的情况下,这是int s。

如果设置dtype=np.float32则可以使示例正常工作:

import numpy as np lst = np.asarray(list(range(10)), dtype=np.float32) print "lst before assignment: ", lst lst[:4] = [0.3, 0.5, 10.6, 0.2]; print "lst after assignment: ", lst

在任务之前:[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]

任务完成后:[0.30000001 0.5 10.60000038 0.2 4. 5. 6. 7. 8. 9.]

有关详细信息,请在此处找到文档。

The answer is clear once numpy.asarray's signature is seen:

numpy.asarray(a, dtype=None, order=None)

If dtype isn't set, it is inferred by the data provided. In your case, it was ints.

You could make your example work if you set dtype=np.float32:

import numpy as np lst = np.asarray(list(range(10)), dtype=np.float32) print "lst before assignment: ", lst lst[:4] = [0.3, 0.5, 10.6, 0.2]; print "lst after assignment: ", lst

lst before assignment: [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]

lst after assignment: [ 0.30000001 0.5 10.60000038 0.2 4. 5. 6. 7. 8. 9. ]

For more information, you can find the docs here.

更多推荐