Run NumPy Online

Concatenate NumPy Arrays

Stack arrays on top of each other or side by side with np.concatenate, vstack and hstack.

  • Intermediate
  • 2 min read
  • 1 runnable example
What you'll learn
  • np.concatenate with axis=0 and axis=1
  • vstack and hstack shortcuts
  • Shape rules for joining
concatenate(([[1, 2], [3, 4]], [[5, 6]]), axis=0)
1
2
3
4
5
6

Join along one axis

Concatenation combines arrays along an existing axis when their other dimensions are compatible.

Key points

  1. axis=0 adds rows; the column counts must match.
  2. axis=1 adds columns; the row counts must match.
  3. np.vstack and np.hstack are shortcuts for the two cases.

When should you use it?

  • Perform numerical operations on many values at once.
  • Process arrays, matrices, and scientific data efficiently.
  • Prepare data for data science and machine learning.

Example code

Run code →
main.py
import numpy as np

first = np.array([[1, 2], [3, 4]])
second = np.array([[5, 6]])

print(np.concatenate((first, second), axis=0))
Get a Run button for this example

Result of running the code

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

Code explanation

Axis zero adds rows. Both input arrays have the same number of columns, so they can be stacked vertically.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input shape and dtype.
  2. Try negative, floating-point, and missing values.
  3. Apply the operation to larger multidimensional arrays and measure performance.
Run in the Python compiler →