Home »
Python »
Python Programs
How to get a contiguous array in NumPy?
Learn, how to get a contiguous array in Python NumPy?
By Pranit Sharma Last updated : December 26, 2023
NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.
Getting a contiguous array in NumPy
A contiguous array type is a specialized array that always stores its elements in a contiguous region of memory.
To get a contiguous array in numpy, we use numpy.ascontiguousarray() which returns a contiguous array (ndim >= 1) in memory (C order).
Python numpy.ascontiguousarray() Method
The numpy.ascontiguousarray() method returns a contiguous array (ndim >= 1) in memory (C order).
Syntax of ascontiguousarray() Method
Below is the syntax of numpy.ascontiguousarray() method:
numpy.ascontiguousarray(a, dtype=None, *, like=None)
Parameters of ascontiguousarray() Method
Below is the parameters of numpy.ascontiguousarray() method:
- a: input array
- dtype: data type of returned array, can be str or dtype object.
- like: Reference object to allow the creation of arrays which are not NumPy arrays.
Return Value of ascontiguousarray() Method
The numpy.ascontiguousarray() method return an contiguous array of same shape and content as a, with type dtype if specified.
Let us understand with the help of an example,
Python code to get a contiguous array in NumPy
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.ones((2, 3), order='F')
# Display original array
print("Original Array:\n",arr,"\n")
# Creating a contiguous array
res = np.ascontiguousarray(arr)
# Display result
print("append result:\n",res,"\n")
# Check if res is contiguous or not
print("Is res contiguous:\n",res.flags['C_CONTIGUOUS'])
Output
In this example, we have used the following Python basic topics that you should learn:
Web Reference
Python NumPy Programs »
Advertisement
Advertisement