1

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.

2
  • 1
    Just specify the dtype at the first step : np.array([[0 for i in range(29)]],dtype=float). Commented Mar 20, 2017 at 22:13
  • @Divakar, such an easy fix! I feel stupid now. Thanks a lot. Commented Mar 20, 2017 at 22:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.