Last updated

Joining Arrays

Definition: Joining combines two or more arrays into one. concatenate joins along an existing axis; vstack and hstack stack vertically and horizontally.

Example 1 — concatenate (1D)

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

Example 2 — stacking

import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.vstack((a, b)))   # stack as rows
print(np.hstack((a, b)))   # join end to end

vstack makes a 2D array with each input as a row; hstack lays them side by side.

Joining 2D arrays

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

💡 Tip: axis=0 works down the rows, axis=1 across the columns.

Try it Yourself
Output

          
Ad · responsive