Open In App

Joining NumPy Array

Last Updated : 13 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Joining NumPy arrays means combining multiple arrays into one larger array. For example, joining two arrays [1, 2] and [3, 4] results in a combined array [1, 2, 3, 4]. Let’s explore some common ways to join arrays using NumPy.

1. Using numpy.concatenate()

numpy.concatenate() joins two or more arrays along an existing axis without adding new dimensions. It is fast and efficient for straightforward array joining.

Python
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])

res = np.concatenate((a, b))
print(res)

Output
[1 2 3 4]

This code combines them into one longer list [1, 2, 3, 4] using NumPy’s concatenate function which just sticks the arrays together end to end.

2. Using numpy.hstack() / numpy.vstack() / numpy.dstack()

numpy.hstack(), numpy.vstack() and numpy.dstack() are convenient wrappers around concatenate for stacking arrays horizontally, vertically or depth-wise making code more readable and expressive.

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

res_h = np.hstack((a, b))
print("np.hstack: ", res_h)

res_v = np.vstack((a, b))
print("np.vstack: ", res_v)

res_d = np.dstack((a,b))
print("np.dstack: ", res_d)

Output
np.hstack:  [1 2 3 4 5 6]
np.vstack:  [[1 2 3]
 [4 5 6]]
np.dstack:  [[[1 4]
  [2 5]
  [3 6]]]
  • hstack joins them into one long array.
  • vstack stacks them as rows in a 2D array.
  • dstack stacks them depth-wise to form a 3D array.

3. Using numpy.stack()

numpy.stack() joins arrays along a new axis, increasing the dimensionality. It is useful when you want to combine arrays but keep them separated along a new dimension.

Python
import numpy as np

a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])

res = np.stack((a, b), axis=1)
print(res)

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

stack with axis=1 makes the code combines them by pairing elements side-by-side into rows, creating a 2D array where each row contains one element from each array.

4. Using numpy.block()

numpy.block() builds arrays from nested blocks like assembling matrices from smaller sub-arrays. It provides flexible and powerful ways to create complex array layouts.

Python
import numpy as np
b1 = np.array([[1, 1], [1, 1]])
b2 = np.array([[2, 2, 2], [2, 2, 2]])
b3 = np.array([[3, 3], [3, 3], [3, 3]])
b4 = np.array([[4, 4, 4], [4, 4, 4], [4, 4, 4]])

res = np.block([
    [b1, b2],
    [b3, b4]
])

print(res)

Output
[[1 1 2 2 2]
 [1 1 2 2 2]
 [3 3 4 4 4]
 [3 3 4 4 4]
 [3 3 4 4 4]]

Four small arrays are arranged as blocks b1 and b2 side by side on top, b3 and b4 side by side below. np.block joins them into one large array preserving this layout.


Next Article
Practice Tags :

Similar Reads