NumPy: numpy.asfortranarrray() function
numpy.asfortranarrray() function
The numpy.asfortranarrray() function is used to create a new array by converting the input array to the Fortran-contiguous memory layout.
This function is useful when working with Fortran code or libraries that require column-major order for efficient processing. It can also be used to improve the performance of array operations by ensuring that the memory layout of the array is optimized for the specific operation.
Syntax:
numpy.asfortranarray(a, dtype=None)
Parameters:
Name | Description | Required / Optional |
---|---|---|
a | Input array. | Required |
dtype | By default, the data-type is inferred from the input data. | Optional |
Return value:
out : ndarray The input a in Fortran, or column-major, order.
Example: Creating a Fortran-contiguous array from a C-contiguous array using numpy.asfortranarray()
>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> b = np.asfortranarray(a)
>>> a.flags['F_CONTIGUOUS']
False
>>> b.flags['F_CONTIGUOUS']
True
In the above code, a 3x3 array 'a' is created using numpy.arange() and numpy.reshape() functions. The 'a' array is then passed as an argument to the numpy.asfortranarray() function, which returns a new array 'b' that is Fortran-contiguous.
To check if an array is Fortran-contiguous, we can use the 'flags' attribute of the ndarray object, which returns a dictionary containing various information about the array. The 'F_CONTIGUOUS' key in the dictionary is set to True if the array is Fortran-contiguous, and False otherwise. In this code, we check the 'F_CONTIGUOUS' flag of both 'a' and 'b' arrays, and observe that 'a' is not Fortran-contiguous, whereas 'b' is Fortran-contiguous.
Python - NumPy Code Editor:
Previous: asfarray()
Next: ascontiguousarray()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/numpy/manipulation/asfortranarray.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics