In Python, for some cases, we need a one-dimensional array rather than a 2-D or multi-dimensional array. For this purpose, the numpy module provides a function called numpy.ndarray.flatten(), which returns a copy of the array in one dimensional rather than in 2-D or a multi-dimensional array.
ndarray.flatten(order='C')
order: {'C', 'F', 'A', 'K'}(optional)
If we set the order parameter to 'C', it means that the array gets flattened in row-major order. If 'F' is set, the array gets flattened in column-major order. The array is flattened in column-major order only when 'a' is Fortran contiguous in memory, and when we set the order parameter to 'A'. The last order is 'K', which flatten the array in same order in which the elements occurred in the memory. By default, this parameter is set to 'C'.
y: ndarray
This function returns a copy of the source array, which gets flattened into one-dimensional.
import numpy as np a = np.array([[1,4,7], [2,5,8],[3,6,9]]) b=a.flatten() b
Output:
In the above code
In the output, it shows a ndarray, which contains elements of the multi-dimensional array into 1-D.
import numpy as np a = np.array([[1,4,7], [2,5,8],[3,6,9]]) b=a.flatten('C') b
Output:
In the above code
In the output, it shows a ndarray, which contains elements of the multi-dimensional array into 1-D.
import numpy as np a = np.array([[1,4,7], [2,5,8],[3,6,9]]) b=a.flatten('F') b
Output:
import numpy as np a = np.array([[1,4,7], [2,5,8],[3,6,9]]) b=a.flatten('A') b
Output:
import numpy as np a = np.array([[1,4,7], [2,5,8],[3,6,9]]) b=a.flatten('K') b
Output: