Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation of 2 1D `numpy` Arrays Along 2nd Axis

Tags:

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?

like image 496
ricky_hehe Avatar asked Feb 15 '16 03:02

ricky_hehe


1 Answers

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]]) 
like image 152
hpaulj Avatar answered Sep 18 '22 12:09

hpaulj