toom - 9 months ago 244

Python Question

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?

Answer

Because both `a`

and `b`

have only one axis, as their shape is `(3)`

, and the axis parameter specifically refers to the axis of the elements to concatenate.

this example should clarify what `concatenate`

is doing with axis. Take two vectors with two axis, with shape `(2,3)`

:

```
a = np.array([[1,5,9],[2,6,10]])
b = np.array([[3,7,11],[4,8,12]])
```

concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):

```
print concatenate((a,b),axis=0)
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
```

concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):

```
print concatenate((a,b),axis=1)
array([[ 1, 5, 9, 3, 7, 11],
[ 2, 6, 10, 4, 8, 12]])
```

to obtain the output you presented, you can use

```
a = np.array([1,2,3])
b = np.array([4,5,6])
vstack((a,b))
```

You can still do it with concatenate, but it takes longer:

```
a=a.reshape(1,3)
b=b.reshape(1,3)
print concatenate((a,b))
```