DPdl
DPdl

Reputation: 755

Replacing elements of a multidimensional array

I am trying to replace some elements of a 29 x 1 matrix with elements from a list.

import numpy as np

initAmount = np.array([[0 for i in range(29)]])
initialAmount = np.ndarray.transpose(initAmount)
ind = [0.04, 0.02, 0.03]
#ind = [1,2,3]
initialAmount[0,0] = float(ind[0])
initialAmount[1,0] = float(ind[1])
initialAmount[2,0] = float(ind[2])
print(initialAmount)

Unfortunately, this is not working like it is supposed to. initialAmount after running the code should be [[0.04],[0.02],[0.03],[0],...], and not [[0],[0],[0]....], which is the result I am getting. The code works fine when my list ind = [1,2,3]. So, I am assuming there is an error with the precision, but I have no idea how to fix this.

Any help will be appreciated.

Upvotes: 1

Views: 859

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

Just make your array usin the built-in numpy.zeros which takes a dtype and shape parameter, greatly simplifyying what you are trying to accomplish:

>>> init = np.zeros((29, 1), dtype=float)
>>> ind = [0.04, 0.02, 0.03]
>>> init[0,0] = ind[0]
>>> init[1,0] = ind[1]
>>> init[2,0] = ind[2]
>>> init
array([[ 0.04],
       [ 0.02],
       [ 0.03],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ]])
>>>

Note, by default np.zeros using float dtype. But it doesn't hurt to be explicit.

Upvotes: 2

Related Questions