NumPy: Joining NumPy Arrays

As we know, joining means bringing elements of two or more arrays whose dimension is the same in a single array.
In Numpy there are various functions available in Numpy Packages that can be used to join two or more arrays.

numpy.concatenate:

numpy.concatenate is used to join two or more arrays of the same dimension and same shape along the given axis.

Syntax:

numpy.concatenate((array1, array2, ...), axis=0)

Example:

For 1-D Array:

import numpy as np
a=np.arange(1,4)
b=np.arange(5)
c=np.concatenate((a,b))
print(c)

Output:

[1 2 3 0 1 2 3 4]

For 2-D Array:

When axis=0

import numpy as np
a=np.array([[1,2],[3,4]])#(2,2)
b=np.array([[5,6]])#(1,2)
c=np.concatenate((a,b))#axis=0 
print(c)

Output:

[[1 2]
 [3 4]
 [5 6]]

When axis=1

import numpy as np
a=np.array([[1,2],[3,4]])#axis=(2,2)
b=np.array([[5,6]])#axis(1,2)
c=np.concatenate((a,b),axis=1)#concatenating along axis=1
print(c)

Output:

ValueError: all the input array dimensions for the concatenation axis must match 
exactly, but along dimension 0, the array at index 0 has size 2 and the array at 
index 1 has size 1.

To avoid Error:

import numpy as np
a=np.array([[1,2],[3,4]])#axis=(2,2)
b=np.array([[5,6]])#axis(1,2)
c=np.concatenate((a,b.T),axis=1)#b axis will change from(1,2) to (2,1)
print(c)

Output:

[[1 2 5]
 [3 4 6]]
Thu, 09/02/2021 - 11:24

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.