Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate two one-dimensional to two columns array

a = np.array([1, 2, 3])
aa = np.array([1], [2], [3])
b = np.array([1, 2, 3])
bb = np.array([1], [2], [3])
np.concatenate((a, b), axis = 1)
array([1, 2, 3, 1, 2, 3])     # It's ok, that's what I was expecting
np.concatenate((a, b), axis = 0)
array([1, 2, 3, 1, 2, 3])     # It's not ok, that's not what I was expecting

I was expecting:

array([[1, 2, 3],
       [1, 2, 3]])

even with aa and bb I get the same inconsistency. so is there a simple solution to concatenate along axis 0 two one-dimensional arrays?

like image 636
user1850133 Avatar asked Jan 23 '13 15:01

user1850133


People also ask

Can we concatenate the 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). The axis along which the arrays will be joined.

How do I combine two 1d arrays?

Joining Arrays Using Stack Functions We can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis. If axis is not explicitly passed it is taken as 0.

Can I concatenate arrays?

concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


1 Answers

Note that a and b are both one-dimensional; there's no axis 1 to concatenate along. You want vstack:

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = a.copy()
>>> np.vstack([a,b])
array([[1, 2, 3],
       [1, 2, 3]])

Alternatively, you could reshape a and b first:

>>> np.concatenate([a[np.newaxis,:],b[np.newaxis,:]],axis = 0)
array([[1, 2, 3],
       [1, 2, 3]])
like image 190
John Vinyard Avatar answered Sep 30 '22 10:09

John Vinyard