15.3 C
London
Tuesday, June 17, 2025
HomePythonOperations in PythonHow to Concatenate Arrays in Python (With Examples)

How to Concatenate Arrays in Python (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

The easiest way to concatenate arrays in Python is to use the numpy.concatenate function, which uses the following syntax:

numpy.concatenate((a1, a2, ….), axis = 0)

where:

  • a1, a2 …: The sequence of arrays
  • axis: The axis along which the arrays will be joined. Default is 0.

This tutorial provides several examples of how to use this function in practice.

Example 1: Concatenate Two Arrays

The following code shows how to concatenate two 1-dimensional arrays:

import numpy as np

#create two arrays
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([6, 7, 8])

#concatentate the two arrays
np.concatenate((arr1, arr2))

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

The following code shows how to concatenate two 2-dimensional arrays:

import numpy as np

#create two arrays
arr1 = np.array([[3, 5], [9, 9], [12, 15]])
arr2 = np.array([[4, 0]])

#concatentate the two arrays
np.concatenate((arr1, arr2), axis=0)

array([[3, 5],
       [9, 9],
       [12, 15],
       [4, 0]])

#concatentate the two arrays and flatten the result
np.concatenate((arr1, arr2), axis=None)

array([3, 5, 9, 9, 12, 15, 4, 0])

Example 2: Concatenate More Than Two Arrays

We can use similar code to concatenate more than two arrays:

import numpy as np

#create four arrays
arr1 = np.array([[3, 5], [9, 9], [12, 15]])
arr2 = np.array([[4, 0]])
arr3 = np.array([[1, 1]])
arr4 = np.array([[8, 8]])

#concatentate all the arrays
np.concatenate((arr1, arr2, arr3, arr4), axis=0)

array([[3, 5],
       [9, 9],
       [12, 15],
       [4, 0],
       [1, 1],
       [8, 8]])

#concatentate all the arrays and flatten the result
np.concatenate((arr1, arr2, arr3, arr4), axis=None)

array([3, 5, 9, 9, 12, 15, 4, 0, 1, 1, 8, 8])

Additional Resources

The following tutorials explain how to perform similar operations in NumPy:

How to Create a Pandas DataFrame from a NumPy Array
How to Add a Numpy Array to a Pandas DataFrame

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories