What is the numpy.ndarray.flatten() method in Python?
Overview
The ndarray.flatten() method in Python is used to return a copy of a given array in such a way that it is collapsed into one dimension.
Syntax
ndarray.flatten(order='C')
Syntax for the ndarray.flatten() method
Parameter value
The ndarray.flatten() method takes an optional parameter value, orfer, which represents the order to which the array is to be flattened. The different orders are:
'C': This is to flatten the array in row-major order.'F': This is to flatten the array in column-major order.'A': This is to flatten the array in column-major order, if the input array is Fortran contiguous in memory, and row-major order if otherwise.'K': This is to flatten the array in the order in which its elements occur in memory.
The default value is 'C'.
Example
import numpy as np# creating an input arraymyarray = np.array([[1,2,3],[4,5,6]])# to flatten the array in F-orderprint(myarray.flatten('F'))
Code explanation
- Line 1: We import the
numpymodule. - Line 3: We create an input array,
myarray, using thearray()function. - Line 6: We implement the
ndarray.flatten()method on the input array. We print the result to the console.