Numpy Issue About Autoupdate Array When Subtracting Float Number To Int Array
Hi I'm trying to subtract a number for a entire column on a Numpy 2D array, and put the resultant values into the same column, but when the subtracted number is float and the array
Solution 1:
NumPy arrays have a fixed datatype (dtype
) which is inferred from the initialization data if you don't specify it yourself. It won't change unless you tell it to, so in your first case:
a[:,1] - 0.5
you're OK because you create a new array with a new, float
dtype
inferred as necessary from the calculation(the original a
is not changed.) In your second, you are actually trying to change the values in a
, which is an integer array, so the result of the calculation is cast to an integer: int(2-0.5)
is 1
, for example.
To do float arithmetic on your array, upcast it to float
explicitly with astype
:
In [32]: a.astype('float') - 0.5
Out[32]:
array([[ 0.5, 1.5],
[ 1.5, 2.5],
[ 2.5, 3.5]])
Post a Comment for "Numpy Issue About Autoupdate Array When Subtracting Float Number To Int Array"