Why the numpy is not assigned correctly?

I came up with this problem when working with numpy.

I declared a variable:

x = np.array([[1,2,3,4,5],[1,2,3,4,5]])

Then i reassigned the first row:

x[0] = [0,0,1,-0.8,-0.1]

When i printed the array I got this :

print(x)
>>> [[0 0 1 0 0]
     [1 2 3 4 5]]

As it can be seen, the new row does not match with the one I assigned before. It is not a problem of the printing of the array because I get the same when i look at it closely

print(x[0])
>>> [0 0 1 0 0]
print(x[0][-1])
>>> 0

I runned this in google colab and in my python console and I still get the same

Is there any explanation or solution to this problem?

Upvotes: 0

Views: 452

Answers (2)

Alex D
Alex D

Reputation: 46

As the answerer above mentioned, the numpy array is of type int, rather than type float. When you assign a float into the int, numpy automatically casts those values to ints, which is why the values are changing.

Alternatively, you can cast the array to float, especially if you don't have control over the input (ie it is within an argument).

import numpy as np
x = np.array([[1,2,3,4,5],[1,2,3,4,5]]).astype(np.float32)
x[0] = [0,0,1,-0.8,-0.1]
print(x)

[[ 0.   0.   1.  -0.8 -0.1]
[ 1.   2.   3.   4.   5. ]]

Upvotes: 1

Ibrahim Berber
Ibrahim Berber

Reputation: 860

When instantiating numpy array, you can specify its dtype.

import numpy as np

x = np.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], dtype=float)

x[0] = [0,0,1,-0.8,-0.1]

print(x)

[[ 0.   0.   1.  -0.8 -0.1]
 [ 1.   2.   3.   4.   5. ]]

Upvotes: 2

Related Questions