How To Concatenate Arrays In Python

In this tutorial, we will learn how to concatenate arrays in Python using different methods. Concatenating arrays means combining two or more arrays together to form a single array.

This operation is very useful when dealing with large datasets, as it helps in simplifying data manipulation tasks. So let’s start with some basic methods to concatenate arrays in Python.

Step 1: Using the ‘+’ Operator

One simple way to concatenate two arrays in Python is by using the ‘+’ operator. This operator can be used to concatenate arrays created using Python built-in array module or with Python lists:

array('i', [1, 2, 3, 4, 5, 6])

Step 2: Using the ‘extend()’ Method

Another way to concatenate arrays is using the extend() method, which extends an array by adding the elements from the second array:

array('i', [1, 2, 3, 4, 5, 6])

Step 3: Using NumPy Arrays

Python’s NumPy library allows us to perform a wide range of numerical operations, including array concatenation. The concatenate() function from the NumPy library enables us to concatenate two or more NumPy arrays along a specified axis.

First, let’s install numpy, using the command:

pip install numpy

[1 2 3 4 5 6]

Step 4: Concatenating Multi-Dimensional Arrays

Using NumPy, you can also concatenate multi-dimensional arrays along rows or columns. For this, we need to specify the axis along which arrays should be combined:

[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]

Axis 0 refers to the rows, while axis 1 refers to the columns. If you want to concatenate multi-dimensional arrays horizontally (i.e., along the columns), just set the axis parameter to 1:

[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]]

Full Code

Conclusion

In this tutorial, we have learned various approaches to concatenating arrays in Python. We covered concatenating built-in arrays or lists using the ‘+’ operator, the extend() method, and then using the concatenate() function from the powerful NumPy library.

Finally, we went through how to concatenate multi-dimensional arrays using NumPy’s concatenate() function by specifying the axis parameter.