What is the numpy.ascontiguousarray() function in Python?
Overview
The numpy.ascontiguousarray() function is used to return a contiguous array where the dimension of the array is greater or equal to 1 and stored in memory (C order).
Note: A contiguous array is stored in an unbroken block of memory. To access the subsequent value in the array, we move to the next memory address.
Syntax
numpy.ascontiguousarray(a, dtype=None)
Parameters
The numpy.ascontiguousarray() function takes the following parameter values:
a: This represents the input array.dtype: This represents the data type of the desired array. This is optional.
Return value
The numpy.ascontiguousarray() function returns a contiguous array with the same shape and data type as the input array.
Example
import numpy as np# creating an input arraymyarray = np.arange(6).reshape(2,3)# implementing the numpy.ascontiguousarray() functioncontiguousarray = np.ascontiguousarray(myarray, dtype=np.float32)print(contiguousarray)
Explanation
- Line 1: We import the
numpymodule. - Line 4: We create an input array of sequential integers containing
2arrays with3elements. The output is assigned to a variablemyarray. - Line 7: Using the
numpy.ascontiguousarray()function we make the arraymyarraycontiguous with the float data type. The output is assigned to a new variablecontiguousarray. - Line 9: We print the
contiguousarrayarray.