a shot of dev knowledge

RELATED TAGS

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 array
myarray = np.arange(6).reshape(2,3)

# implementing the numpy.ascontiguousarray() function
contiguousarray = np.ascontiguousarray(myarray, dtype=np.float32)

print(contiguousarray)
Implementing the numpy.ascontiguous() function

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an input array of sequential integers containing 2 arrays with 3 elements. The output is assigned to a variable myarray.
  • Line 7: Using the numpy.ascontiguousarray() function we make the array myarray contiguous with the float data type. The output is assigned to a new variable contiguousarray.
  • Line 9: We print the contiguousarray array.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring