efirvida
efirvida

Reputation: 4855

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 column is integer seems to Numpy convert the resut of the subtraction to int and then update it. Why this happened?

subtracting integer number

In [1]: a = np.array([[1,2],[2,3],[3,4]])

In [2]: a[:,1] - 1
Out[2]: array([1, 2, 3])       # <-- OK!

In [3]: a[:,1] = a[:,1] - 1    # <-- auto-update the array column

In [4]: a
Out[4]:
array([[1, 1],
       [2, 2],
       [3, 3]])                # <-- OK!

subtracting float number

In [1]: a = np.array([[1,2],[2,3],[3,4]])

In [2]: a[:,1] - 0.5
Out[2]: array([ 1.5,  2.5,  3.5])   # <-- seems to be ok

In [3]: a[:,1] = a[:,1] - 0.5       # <-- auto-update the array column

In [4]: a
Out[4]:
array([[1, 1],
       [2, 2],
       [3, 3]])                     # <-- same result a[:,1] = a[:,1] - 1

Upvotes: 0

Views: 1185

Answers (1)

xnx
xnx

Reputation: 25478

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]])

Upvotes: 2

Related Questions