NumPy concatenate in Python

In this tutorial, you will learn about how to concatenate arrays using the NumPy module in Python.

NumPy provides a predefined method named ‘concatenate’ to concatenate 2 arrays.

To use the NumPy module the users have to install the module in their system. One can install this module in their system using pip command.

One can install the NumPy module as shown in the figure: installation of NumPy.

NumPy module

NumPy means Numerical Python but in most cases, we use it for array processing.

To use the NumPy module in Python, we have to import it after installing it by using the import command.

The syntax for importing the NumPy module is:

import numpy

NumPy module has many predefined methods named

  • Array
  • Concatenate etc.,

To know more about the NumPy module please refer to Python programs using NumPy

Concatenate method in NumPy:

The concatenate method in the NumPy module is used to concatenate arrays along the specified axis. The concatenate method takes 2 arguments.

The syntax for Concatenate method:

numpy.concatenate((array1,array2,...), axis)

In the above syntax,

  • array1,array2,… is the array sequence of the same type.
  • axis is the Axis along which the arrays have to be concatenated.

Example: NumPy concatenate in Python

Let us consider an example code using concatenate method in NumPy module

import numpy 
a1=numpy.array([[1,2],[3,4]]) #creating array a1
a2=numpy.array([[5,6],[7,8]]) #creating array a2
#concatenating along axis=0
print(numpy.concatenate((a1,a2)))
#concatenating along axis=1
print(numpy.concatenate((a1,a2),axis = 1))

As a result of the above code, we get the output as

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

Explanation:

  • In the above code a1 and a2 are arrays.
  • By using the concatenate() method the arrays a1 and a2 are joined according to the axis specified.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *