0

I want to create a nxm ndarray with python as follows:

myarray = np.empty(n)
for index in range(5):
    row = do_some_calculations(index)# returns an array of length n
    np.stack[myarray, row]) 

which does not work. I get an error:

ValueError: all the input array dimensions except for the concatenation axis must match exactly

Also, I do not want the first row to be zeros. Do I have to use an if-else statement in the loop or is there a more pythonic way to do that?

Alex
  • 41,580
  • 88
  • 260
  • 469
  • Possible duplicate of [Numpy - add row to array](https://stackoverflow.com/questions/3881453/numpy-add-row-to-array) – chthonicdaemon Mar 18 '18 at 14:14
  • Please show the exact code. The error is hinting at the fact that you're stacking arrays of inequal size so your statement that `do_some_calculations(index)` "returns an array of length n" seems incorrect. – Oliver W. Mar 18 '18 at 14:14
  • Yes it is not the same length... But how to do that in GENERAL? With an additional if? – Alex Mar 18 '18 at 14:22

1 Answers1

1

Try np.vstack instead of np.stack.

Your intent seems to be to append an array at the bottom of an ND-array iteratively (which, by the way, is inefficient, see if you can't generate the entire array in one go). After the first iteration, your myarray's shape will have changed (assuming you re-assigned, which your code did not show) to a 2 by something matrix. The documentation of numpyp.stack states

arrays : sequence of array_like Each array must have the same shape

numpy.vstack is less restrictive.

Oliver W.
  • 13,169
  • 3
  • 37
  • 50
  • What about the first row of zero? – Alex Mar 18 '18 at 14:25
  • If you can't make the initialization more of a one-shot, then how about re-indexing after the loop? Like this: `myarray = myarray[1:,:]`? If it were me, I'd look into generalizing your `do_some_calculations`, but without your actual code (or a minimal version of it) no-one can guess. – Oliver W. Mar 18 '18 at 14:29
  • @Alex, so is your question answered then? If so, please mark your problem as solved by adding the checkmark to the answer. This will signify to others as well that your problem was resolved. – Oliver W. Mar 18 '18 at 17:42