Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation of numpy arrays of unknown dimension along arbitrary axis

I have two arrays A and B of unknown dimensions that I want to concatenate along the Nth dimension. For example:

>>> A = rand(2,2)       # just for illustration, dimensions should be unknown
>>> B = rand(2,2)       # idem
>>> N = 5

>>> C = concatenate((A, B), axis=N)
numpy.core._internal.AxisError: axis 5 is out of bounds for array of dimension 2

>>> C = stack((A, B), axis=N)
numpy.core._internal.AxisError: axis 5 is out of bounds for array of dimension 3

A related question is asked here. Unfortunately, the solutions proposed do not work when the dimensions are unknown and we might have to add several new axis until getting a minimum dimension of N.

What I have done is to extend the shape with 1's up until the Nth dimension and then concatenate:

newshapeA = A.shape + (1,) * (N + 1 - A.ndim)
newshapeB = B.shape + (1,) * (N + 1 - B.ndim)
concatenate((A.reshape(newshapeA), B.reshape(newshapeB)), axis=N)

With this code I should be able to concatenate a (2,2,1,3) array with a (2,2) array along axis 3, for instance.

Are there better ways of achieving this?

ps: updated as suggested the first answer.

like image 719
Miguel Avatar asked Oct 28 '13 13:10

Miguel


People also ask

Can we concatenate arrays with different dimensions?

Join a sequence of arrays along an existing axis. The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

Can you concatenate NumPy arrays?

You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array.

What is Axis in concatenate in NumPy?

Numpy concatenate is like “stacking” numpy arrays The axis that we specify with the axis parameter is the axis along which we stack the arrays. So when we set axis = 0 , we are stacking along axis 0. Axis 0 is the axis that runs vertically down the rows, so this amounts to stacking the arrays vertically.


1 Answers

This should work:

def atleast_nd(x, n):
    return np.array(x, ndmin=n, subok=True, copy=False)

np.concatenate((atleast_nd(a, N+1), atleast_nd(b, N+1)), axis=N)
like image 124
Eric Avatar answered Oct 20 '22 20:10

Eric