Concatenation of 2-dimensional arrays along the 2nd axis

Performance

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

leads to

 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 he report that axis 1 is outside the boundaries?

+9
source share
5 answers

Your name explains this - the 1st array does not have a 2nd axis!

But, having said that, on my system, as on @Oliver W. s, it does not cause 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 expect 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 seems concatenate ignoring the axis parameter when arrays are 1d. I do not know if it was something new in my version 1.9 or something old.

For more control, consider using the vstack and hstack , which expand the size of the array if necessary:

 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]]) 
+9
source

This is due to the Numpy way of representing one-dimensional arrays. The following use of 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 it was first created:

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

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

 t1.reshape(-1,1).shape >>(9,1) 
+6
source

It is better to use another Numpy function called numpy.stack .
It behaves like a MATLAB cat .

The numpy.stack function numpy.stack not require arrays to have a dimension associated with them.

+4
source

This is because you need to change it into two dimensions, because one dimension cannot be combined. By doing this, you can add an empty column. This 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) 
0
source

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)) 

What are the results

 [[ 1 11] [ 2 12] [ 3 13] [ 4 14] [ 5 15] [ 6 16] [ 7 17] [ 8 18] [ 9 19]] 
0
source

Source: https://habr.com/ru/post/1243021/


All Articles