How to Use the Numpy concatenate() Function in Python

09/15/2021

Contents

In this article, you will learn how to use the Numpy concatenate() function in Python.

Numpy concatenate() Function

The numpy.concatenate() function is used to concatenate two or more arrays along a specified axis.

Syntax
numpy.concatenate((array1, array2, ...), axis=0, out=None)
Parameters
  • array1, array2, ...: Two or more arrays to be concatenated. They must have the same shape, except in the dimension corresponding to the axis argument.
  • axis: The axis along which the arrays will be joined. Default is 0.
  • out: If provided, the result will be stored in this array.
Example
import numpy as np

# Concatenate two 1D arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a, b))
print(c)  
# Output: [1 2 3 4 5 6]

# Concatenate two 2D arrays along axis=0
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
c = np.concatenate((a, b), axis=0)
print(c)  # Output: [[1 2]
          #          [3 4]
          #          [5 6]]

# Concatenate two 2D arrays along axis=1
a = np.array([[1, 2], [3, 4]])
b = np.array([[5], [6]])
c = np.concatenate((a, b), axis=1)
print(c)  # Output: [[1 2 5]
          #          [3 4 6]]

In the first example, two 1D arrays are concatenated into a single 1D array.

In the second example, two 2D arrays are concatenated along axis=0, which results in a 3×2 array.

In the third example, two 2D arrays are concatenated along axis=1, which results in a 2×3 array.