How do you concatenate arrays in Python, and what are some examples?

Concatenation is the process of joining two or more arrays in Python. This operation is performed using the ‘+’ operator, which combines the elements of the arrays into a single array. For example, if we have two arrays, A = [1, 2, 3] and B = [4, 5, 6], concatenating them would result in a new array, C = [1, 2, 3, 4, 5, 6]. This process can be extended to any number of arrays by using the ‘+’ operator between each array. Concatenation is commonly used in data manipulation and analysis tasks, such as merging multiple datasets or combining arrays with different attributes. Additionally, it can also be used for tasks such as creating new arrays from existing ones or reshaping arrays. Overall, concatenation is a versatile and useful tool in Python for manipulating and organizing data.

Concatenate Arrays in Python (With Examples)


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:

x