Alex
Alex

Reputation: 44305

How to fix error when concatenating two numpy arrays?

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...?

Upvotes: 0

Views: 1455

Answers (1)

unutbu
unutbu

Reputation: 879361

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)

Upvotes: 3

Related Questions