NumPy: Joining Arrays Using Stack Functions

Profile picture for user devanshi.srivastava
Submitted by devanshi.srivastava on

stack() function is available in Numpy Package. It is used to join two or more arrays along a new axis. It works the same as concatenate.

Syntax:

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

Example:

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

Output:

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

Stacking along Rows:

We use hstack() to do stacking along a row.

Example:

For 1-D Arrays

import numpy as np
a=np.arange(6)
b=np.arange(5)
print(np.hstack((a,b)))#Here a(1,6) and b(1,5) along axis=0

Output:

[0 1 2 3 4 5 0 1 2 3 4]

For 2-D Arrays

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

Output:

[[1 2 5 6]

[3 4 7 8]]

Stacking along Columns:

We use vstack() to do stacking along a column.

Example:

For 1-D Array:

import numpy as np
a=np.arange(5)
b=np.arange(5)
print(np.vstack((a,b)))

Output:

[[0 1 2 3 4]
 [0 1 2 3 4]]

For 2-D Array:

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

Output:

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

Stacking along Height:

We use a dstack() to perform stacking along height(same as depth).

Example:

For 1-D Array:

import numpy as np
a=np.arange(5)
b=np.arange(5)
print(np.dstack((a,b)))

Output:

[[[0 0]
  [1 1]
  [2 2]
  [3 3]
  [4 4]]]

For 2-D Array:

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

Output:

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