Concatenation of 2 1D `numpy` Arrays Along 2nd Axis
Asked Answered
P

5

25

Executing

import numpy as np
t1 = np.arange(1,10)
t2 = np.arange(11,20)

t3 = np.concatenate((t1,t2),axis=1)

results in a

Traceback (most recent call last):

  File "<ipython-input-264-85078aa26398>", line 1, in <module>
    t3 = np.concatenate((t1,t2),axis=1)

IndexError: axis 1 out of bounds [0, 1)

why does it report that axis 1 is out of bounds?

Pasha answered 15/2, 2016 at 3:26 Comment(0)
K
20

Your title explains it - a 1d array does not have a 2nd axis!

But having said that, on my system as on @Oliver W.s, it does not produce an error

In [655]: np.concatenate((t1,t2),axis=1)
Out[655]: 
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 11, 12, 13, 14, 15, 16, 17, 18,
       19])

This is the result I would have expected from axis=0:

In [656]: np.concatenate((t1,t2),axis=0)
Out[656]: 
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 11, 12, 13, 14, 15, 16, 17, 18,
       19])

It looks like concatenate ignores the axis parameter when the arrays are 1d. I don't know if this is something new in my 1.9 version, or something old.

For more control consider using the vstack and hstack wrappers that expand array dimensions if needed:

In [657]: np.hstack((t1,t2))
Out[657]: 
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 11, 12, 13, 14, 15, 16, 17, 18,
       19])

In [658]: np.vstack((t1,t2))
Out[658]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9],
       [11, 12, 13, 14, 15, 16, 17, 18, 19]])
Kathlyn answered 15/2, 2016 at 4:6 Comment(0)
A
16

This is because of Numpy's way of representing 1D arrays. The following using reshape() will work:

t3 = np.concatenate((t1.reshape(-1,1),t2.reshape(-1,1),axis=1)

Explanation: This is the shape of the 1D array when initially created:

t1 = np.arange(1,10)
t1.shape
>>(9,)

'np.concatenate' and many other functions don't like the missing dimension. Reshape does the following:

t1.reshape(-1,1).shape
>>(9,1) 
Asthenia answered 21/7, 2018 at 0:56 Comment(0)
H
11

If you need an array with two columns you can use column_stack:

import numpy as np
t1 = np.arange(1,10)
t2 = np.arange(11,20)
np.column_stack((t1,t2))

Which results

[[ 1 11]
 [ 2 12]
 [ 3 13]
 [ 4 14]
 [ 5 15]
 [ 6 16]
 [ 7 17]
 [ 8 18]
 [ 9 19]]
Haggard answered 12/7, 2018 at 15:52 Comment(0)
D
5

You better use a different function of Numpy called numpy.stack.
It behaves like MATLAB's cat.

The numpy.stack function doesn't require the arrays to have the dimension they are concatenated along.

Dinosaurian answered 18/11, 2017 at 16:41 Comment(0)
Q
0

This is because you need to change it into two dimensions because one dimesion cannot concatenate with. By doing this you can add an empty column. It works if you run the following code:

import numpy as np 
t1 = np.arange(1,10)[None,:]
t2 = np.arange(11,20)[None,:]
t3 = np.concatenate((t1,t2),axis=1)
print(t3)
Quarterly answered 18/5, 2018 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.