NumPy concatenate() function
In this tutorial, we will cover the concatenate()
function of the NumPy library.
The concatenate()
function is mainly used in order to combine two or more NumPy arrays together. ence we can say that the concatenate()
function can be used to join a sequence of arrays along an existing axis.
-
With the help of this function you can concatenate arrays together either horizontally or vertically.
-
Concatenation of two numpy arrays simply means their stacking.
-
This function joins two or more arrays having same shape and along the specified axis.
Syntax of numpy.concatenate()
:
The syntax required to use this function is as follows:
numpy.concatenate((a1, a2, ...), axis=0, out=None)
Parameters:
Let us take a look at the parameters of this function:
-
(a1, a2 , ...)
This parameter indicates the sequence of array like structures or arrays. Here a1
, a2
, ... are the arrays having the same shape, which are to be concatenated together.
-
axis
This parameter is used to define the axis along which the array will be concatenated. The default value of this parameter is 0.
-
out
It is an optional parameter, which if provided then it simply indicates the destination where the result will be placed. If no out
argument is specified then the shape must be correct, and should match with that of what concatenate would have returned.
Returned Values:
The concatenate()
function will return the concatenated array as a result.
Example 1: With axis=0
Let us have a look at the basic example of this function and the code snippet for the same is as follows:
import numpy as np
array1 = np.array([[5, 4], [6, 8]])
print("First Array is:\n",array1)
array2 = np.array([[13, 5], [72, 9]])
print("Second Array is :\n",array2)
out= np.concatenate((array1, array2), axis = 0)
print("The result of concatenation is :")
print (out)
Example 2: With Axis=1
Below we have another example where we will take axis=1:
import numpy as np
array1 = np.array([[5, 4], [6, 8]])
print("First Array is:\n",array1)
array2 = np.array([[13, 5], [72, 9]])
print("Second Array is :\n",array2)
out= np.concatenate((array1, array2), axis = 1)
print("The result of concatenation is :")
print (out)
Summary
This tutorial was all about concatenate()
function in the Numpy library. We haave covered how it is used with its syntax, its parameters and values returned by this function.