0

I am trying the following:

rands = np.empty((0, 10))
rand = np.random.normal(1, 0.1, 10)
rands = np.concatenate((rands,rand),axis=0)

which gives me the following error:

ValueError: all the input arrays must have same number of dimensions

But why is this error? Why can't I append a new row rand into the matrix rands with this command?

Remark:

I can 'fix' this by using the following command:

rands = np.concatenate((rands,rand.reshape(1, 10)),axis=0)

but it looks not pythonic anymore, but cumbersome...

Maybe there is a better solution with less brackets and reshaping...?

6
  • Well although rands has initially an empty row it is still 2 dimensional the shape is (0,10) which is why it borks Commented Nov 10, 2016 at 9:15
  • Yes, and a row is one-dimensional with 10 elements. I don't understand what the problem is here... Commented Nov 10, 2016 at 9:16
  • Not in numpy's eyes it isn't you'd still get the same error with rands = np.empty((1, 10)) Commented Nov 10, 2016 at 9:17
  • what about: rands = np.empty((1,10)) rands = np.concatenate((rands[0],rand),axis=0) Commented Nov 10, 2016 at 9:19
  • no does not work. I will add more rows later, I have to repeat this concatenate line multiple times, in a loop Commented Nov 10, 2016 at 9:20

1 Answer 1

3

rands has shape (0, 10) and rand has shape (10,).

In [19]: rands.shape
Out[19]: (0, 10)

In [20]: rand.shape
Out[20]: (10,)

If you try to concatenate along the 0-axis, then the 0-axis of rands (of length 0) is concatenated with the 0-axis of rand (of length 10). Pictorially, it looks like this:

rands:

|   |   |   |   |   |   |   |   |   |   |

rand:

|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |

The two shapes do not fit together well because the 1-axis of rands has length 10 and rand lacks a 1-axis.

To fix the problem, you could promote rand to a 2D array of shape (1, 10):

In [21]: rand[None,:].shape
Out[21]: (1, 10)

So that the 10 items in rand are now laid out along the 1-axis. Then

rands = np.concatenate((rands,rand[None,:]), axis=0)

returns an array of shape (1, 10)

In [26]: np.concatenate((rands,rand[None,:]),axis=0).shape
Out[26]: (1, 10)

Alternatively, you could use row_stack without promoting rand to a 2D array:

In [28]: np.row_stack((rands,rand)).shape
Out[28]: (1, 10)
Sign up to request clarification or add additional context in comments.

1 Comment

I like row_stack. And now it looks more pythonic.Thanks!

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.