NumPy concatenate()

Summary: in this tutorial, you’ll learn how to use the NumPy concatenate() function to join elements of two or more arrays into a single array.

Introduction to the NumPy concatenate() function

The concatenate() function allows you to join two or more arrays into a single array. Here’s the basic syntax of the concatenate() function:

np.concatenate((a1,a2,...),axis=0)Code language: Python (python)

In this syntax, the concatenate() function joins the elements of the sequence of arrays (a1, a2, …) into a single array. The arrays in the sequence must have the same shape.

The axis specifies the axis along which the funciton will join the arrays. If the axis is None, the function will flatten the arrays before joining.

The concatenate() function returns the concatenated array.

NumPy concatenate() function examples

Let’s take some examples of using the concatenate() function.

1) Using the concatenate() function to join two 1D arrays

The following example uses the concatenate() function to join elements of two 1D arrays:

import numpy as np

a = np.array([1, 2])
b = np.array([3, 4])

c = np.concatenate((a, b))
print(c)Code language: Python (python)
numpy concatenate 1d arrays

Output:

[1 2 3 4]Code language: Python (python)

In this example, the concatenate() function joins the elements in the array a and b into a single array c.

2) Using the concatenate() function to join two 2D arrays

The following example uses the concatenate() function to join two 2D arrays:

import numpy as np

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

c = np.concatenate((a, b))
print(c)Code language: Python (python)

Output:

[[1 2] 
 [3 4] 
 [5 6] 
 [7 8]]Code language: Python (python)
numpy concatenate 2d arrays

The output shows that the concatenate() function joins two arrays vertically because by default the axis argument is zero.

If the axis is one, the concatenate() funciton will join two arrays horizontally. For example:

import numpy as np

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

c = np.concatenate((a, b), axis=1)
print(c)Code language: Python (python)
numpy concatenate 2d arrays

Output:

[[1 2 5 6] 
 [3 4 7 8]]Code language: Python (python)

Summary

  • Use the numpy concatenate() function to join elements of a sequence of arrays into a single array.
Did you find this tutorial helpful ?