Home > OS >  Assign a Row of Floats to a 2-D Numpy Array
Assign a Row of Floats to a 2-D Numpy Array

Time:10-09

I am trying to assign floats to a 2-D numpy array. The 2-D array originally consists of integers. After my assignment, the row I intend to change turns completely zeros.

Does anyone know why this is happening?

>>> s=numpy.array([[1,0,0],[1,0,0]])
>>> s[1]=numpy.array([.3,.3,.3])
>>> s
array([[1, 0, 0],
       [0, 0, 0]])

CodePudding user response:

You need to explicitly convert to float:

s = numpy.array([[1,0,0],[1,0,0]])
s = s.astype(numpy.float32, copy=False)
s[1] = numpy.array([.3,.3,.3])

Updated s:

array([[1. , 0. , 0. ],
       [0.3, 0.3, 0.3]], dtype=float32)

CodePudding user response:

This is due to dtype in numpy, Here to understand some executions,

In [1]: s = numpy.array([[1,0,0],[1,0,0]])

In [2]: a = numpy.array([.3,.3,.3])

In [3]: s.dtype
Out[3]: dtype('int64')

In [4]: a.dtype
Out[4]: dtype('float64')

In [5]: a.astype(int)
Out[5]: array([0, 0, 0])

So, while doing s[1] = numpy.array([.3,.3,.3]) it's convert to float64 to int64 that why it's store as [0, 0, 0]

CodePudding user response:

If you intend to keep floats in the future, you may let Python know that by supplying at least one explicit float when creating the object s:

s=numpy.array([[1,0,0],[1,0,0.0]])
  • Related