In this article we will learn and understand what is numpy.concatenate() function and how to use it. We will also get to know the syntax and also the meaning of each parameter used in the function.
Introduction
The numpy.concatenate() function is a part of the Numpy library, and it is very useful to combine arrays in numerical computing. The function is used to join two or more arrays along a specified axis. This axis can be manipulated by the user in the syntax.
This function is extremely useful when you need to combine data for analysis or transformation in Python.
Syntax
numpy.concatenate((array1, array2,...), axis=0, out=none)
Parameters:
- (array1, array2,..): This is the sequence of array which is to be concatenated. the arrays must be of the same shape, except in the dimensions corresponding to the axis.
- axis: [Optional] The axis along which the array will be joined. Default is 0. If it is none it will be flattened.
- out: [Optional] If provided, destination to place the result.
Prerequisites
Before using the numpy.concatenate() function it is important to ensure that the NumPy is installed in the Python environment. If you haven’t installed, then checkout this guide to install it: How to install NumPy.
Basic Example of the numpy.concatenate()
import numpy as np # Creating two arrays array1 = np.array([[1, 2], [3, 4]]) array2 = np.array([[5, 6]]) # Concatenating along axis None result = np.concatenate((array1, array2), axis=None) print(result)
Output:
[1 2 3 4 5 6]
Here first we have installed and imported the numpy library as np. Then created and joined two arrays using the concatenate function.
Example of concatenate function with axis=0
import numpy as np # Creating two arrays array1 = np.array([[1, 2], [3, 4]]) array2 = np.array([[5, 6], [7, 8]]) # Concatenating along axis 0 (rows) result = np.concatenate((array1, array2)) print(result)
Output:
[[1 2] [3 4] [5 6] [7 8]]
Here we have used the same array, but we now have joined using axis=0. Even if value of the array is not mentioned it is taken by default as 0. When concatenate is done with axis=0 then it is joined along rows.
Example of concatenate function with axis=1
import numpy as np # Creating two arrays array1 = np.array([[1, 2], [3, 4]]) array2 = np.array([[5, 6], [7, 8]]) # Concatenating along axis 0 (rows) result = np.concatenate((array1, array2), axis=1) print(result)
Output:
[[1 2 5 6] [3 4 7 8]]
Here also the same array is being joined using the numpy.concatenate() function, but with axis=1. When the arrays are joined using axis=1 then it is joined along columns.
Related Functions
If you are working with arrays, you might find these articles helpful:
- Slicing multidimensional arrays in Python numpy.flip() in Python
- Create an empty and a full NumPy array in Python
- Store different datatypes in one Numpy Array