What is the numpy.asfortranarray() function in Python?
Overview
The asfortranarray() function in Python is used to return an array with ndim >= 1 laid out in a Fortran-style or order in memory.
Note: Fortran order (F-order) is a type of memory layout in which all the elements of a given array are stored in column-major order.
Syntax
numpy.asfortranarray(a, dtype=None, *, like=None)
Syntax for the asfortranarray() function in Python
Parameters
The asfortranarray() function takes the following parameter values:
a(required): This is the input array.dtype(optional): This is the data type of the desired output array. It is inferred from the input array.like(optional): This is an array-like reference object which allows the creation of arrays that are not NumPy arrays.
Example
import numpy as np# creating an input arraya = np.arange(8).reshape(2,4)# implementing the asfortranarray() functionmyarray = np.asfortranarray(a)# check to see if the input array, a, is in F-order memory layoutprint(a.flags['F_CONTIGUOUS'])# check to see if the new array, myarraya, is in F-order memory layoutprint(myarray.flags['F_CONTIGUOUS'])
Explanation
- Line 1: We import the
numpymodule. - Line 3: We create an input array,
a, using thearray()function. - Line 6: We call the
asfortranarray()function and pass the input array,a, as its argument. The result is assigned to a variable,myarray. - Line 9: Using the
flagattribute, we check the memory layout of the input array,a, to see if it is laid out in F-order. - Line 12: Using the
flagattribute, we check the memory layout of the new array,myarray, to see if it is laid out in F-order.