Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Concatenating multidimensional and unidimensional arrays

I have a 2x2 numpy array :

x = array(([[1,2],[4,5]]))

which I must merge (or stack, if you wish) with a one-dimensional array :

y = array(([3,6]))

by adding it to the end of the rows, thus making a 2x3 numpy array that would output like so :

array([[1, 2, 3], [4, 5, 6]])

now the proposed method for this in the numpy guides is :

hstack((x,y))

however this doesn't work, returning the following error :

ValueError: arrays must have same number of dimensions

The only workaround possible seems to be to do this :

hstack((x, array(([y])).T ))

which works, but looks and sounds rather hackish. It seems there is not other way to transpose the given array, so that hstack is able to digest it. I was wondering, is there a cleaner way to do this? Wouldn't there be a way for numpy to guess what I wanted to do?

like image 480
levesque Avatar asked Nov 11 '10 19:11

levesque


People also ask

How do you concatenate two 3d arrays in Python?

One way is to use np. dstack which concatenates the arrays along the third axis (d is for depth). You could also use np. concatenate((a, a), axis=2) .

What is the difference between append and concatenate in NumPy?

append() and np. concatenate(). The append method will add an item to the end of an array and the Concatenation function will allow us to add two arrays together. In concatenate function the input can be any dimension while in the append function all input must be of the same dimension.

Can you combine NumPy arrays?

NumPy's concatenate function can be used to concatenate two arrays either row-wise or column-wise. Concatenate function can take two or more arrays of the same shape and by default it concatenates row-wise i.e. axis=0.


2 Answers

unutbu's answer works in general, but in this case there is also np.column_stack

>>> x
array([[1, 2],
       [4, 5]])
>>> y
array([3, 6])

>>> np.column_stack((x,y))
array([[1, 2, 3],
       [4, 5, 6]])
like image 54
Josef Avatar answered Oct 26 '22 01:10

Josef


Also works:

In [22]: np.append(x, y[:, np.newaxis], axis=1)
Out[22]: 
array([[1, 2, 3],
       [4, 5, 6]])
like image 32
Adobe Avatar answered Oct 26 '22 00:10

Adobe