I tried the following:
>>> a = np.array([1,2,3])
>>> b = np.array([4,5,6])
>>> np.concatenate((a,b), axis=0)
array([1, 2, 3, 4, 5, 6])
>>> np.concatenate((a,b), axis=1)
array([1, 2, 3, 4, 5, 6])
However, I'd expect at least that one result looks like this
array([[1, 2, 3],
[4, 5, 6]])
Why is it not concatenated vertically?
This question is related to
python
arrays
numpy
concatenation
If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate
to perform this operation, I would suggest the use of np.column_stack:
In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
[2, 5],
[3, 6]])
a = np.array([1,2,3])
b = np.array([4,5,6])
np.array((a,b))
works just as well as
np.array([[1,2,3], [4,5,6]])
Regardless of whether it is a list of lists or a list of 1d arrays, np.array
tries to create a 2d array.
But it's also a good idea to understand how np.concatenate
and its family of stack
functions work. In this context concatenate
needs a list of 2d arrays (or any anything that np.array
will turn into a 2d array) as inputs.
np.vstack
first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.
np.stack
is a new function that joins the arrays on a new dimension. Default behaves just like np.array
.
Look at the code for these functions. If written in Python you can learn quite a bit. For vstack
:
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
A not well known feature of numpy is to use r_
. This is a simple way to build up arrays quickly:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.r_[a[None,:],b[None,:]]
print(c)
#[[1 2 3]
# [4 5 6]]
The purpose of a[None,:]
is to add an axis to array a
.
Source: Stackoverflow.com