Why do the decimal numbers disappear when assigning slices in decimal?

from numpy import *
a=array([0.,0.001,0.002])
b=array([[1,11],[2,22],[3,33]])
b[:,1]=a
print b

I expected as a result:

array([[  1. , 0. ],[  2. ,  0.001 ],[  3. , 0.002 ]])

But I got:

array([[ 1 , 0 ], [ 2 , 0 ] , [ 3 , 0 ]])

To get the desired result, I had to enter:

from numpy import *
a=array([0.,0.001,0.002])
b=array([[1,11],[2,22],[3,33]])
b=b.astype(float)
b[:,1]=a
print b

This is mistake? Should the assignment automatically create a numpy array of type float?

+4
source share
2 answers

No, this is not a mistake. From docs :

Note that assignments can lead to changes when assigning higher types to lower types (e.g. float to ints) or even exceptions (assignment is difficult for float or ints)

+3
source

, array b dtype , dtype of a dtype of b.

>>> a.astype(b.dtype) # and when you convert a to dtype of b you get:
array([0, 0, 0])
>>> 
>>> b[:, 1] = a.astype(b.dtype) # I believe this is what is going on under the hood.
>>> b
array([[1, 0],
       [2, 0],
       [3, 0]])
0

Source: https://habr.com/ru/post/1524892/


All Articles