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.


numpy.asfortranarray(a, dtype=None)


Name Description Required /
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']
>>> b.flags['F_CONTIGUOUS']

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()

Follow us on Facebook and Twitter for latest update.