Numpy ndarray.flatten() function in Python
Last Updated :
18 Apr, 2025
The flatten() function is used to convert a multi-dimensional NumPy array into a one-dimensional array. It creates a new copy of the data so that original array stays unchanged. If your array has rows and columns or even more dimensions, then flatten() line up every single value into a straight list, one after another. Example:
Python
import numpy as np
a = np.array([[5, 6], [7, 8]])
res = a.flatten()
print(res)
Explanation: This code creates a 2D NumPy array and uses flatten() to convert it into a 1D array in row-major order. It returns a new array [5, 6, 7, 8] without modifying the original.
Syntax of ndarray.flatten()
array.flatten(order='C')
Parameters: order ({‘C’, ‘F’, ‘A’, ‘K’}) Optional
- 'C': Row-major (C-style) order.
- 'F': Column-major (Fortran-style) order.
- 'A': Column-major if the array is Fortran contiguous, otherwise row-major.
- 'K': Flatten in the order the elements occur in memory.
Returns: A 1D copy of the input array, flattened according to the specified order.
Examples of ndarray.flatten()
Example 1: In this example, we will use the flatten() function with the 'F' parameter to flatten a 2D NumPy array in column-major order (also known as Fortran-style order). This means the function will read the elements column by column, instead of row by row.
Python
import numpy as np
a = np.array([[5, 6], [7, 8]])
res = a.flatten('F')
print(res)
Explanation: flatten('F') convert it into a 1D array in column-major order (Fortran-style). The result is [5, 7, 6, 8], with elements listed column by column.
Example 2: In this example, we will demonstrate how to flatten two 2D NumPy arrays and then concatenate them into a single 1D array using the concatenate() function from NumPy.
Python
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9], [10, 11, 12]])
res = np.concatenate((a.flatten(), b.flatten()))
print(res)
Output[ 1 2 3 4 5 6 7 8 9 10 11 12]
Explanation: This code flattens two 2D NumPy arrays a and b into 1D arrays and then concatenates them. The result is a single 1D array combining the flattened elements of both arrays.
Example 3: In this example, we demonstrate how to flatten a 2D NumPy array and then initialize a new 1D array of the same shape filled with zeros
Python
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
res = np.zeros_like(a.flatten())
print(res)
Explanation: This code creates a new array of the same shape, initialized with zeros using np.zeros_like(). The result is a 1D array of zeros matching the flattened shape of a.
Example 4: In this example, we create a 2D NumPy. Then we apply the max() method to find the maximum value among all the elements in the flattened array.
Python
import numpy as np
a = np.array([[4, 12, 8],[5, 9, 10],[7, 6, 11]])
res = a.flatten().max()
print(res)
Explanation: This code flattens the 2D NumPy array a into a 1D array and then finds the maximum value using .max(). The result is 12, which is the largest value in the flattened array.
Similar Reads
Numpy MaskedArray.flatten() function | Python numpy.MaskedArray.flatten() function is used to return a copy of the input masked array collapsed into one dimension. Syntax : numpy.ma.flatten(order='C') Parameters: order : [âCâ, âFâ, âAâ, âKâ, optional] Whether to flatten in C (row-major), Fortran (column-major) order, or preserve the C/Fortran o
2 min read
numpy.ndarray.flat() in Python The numpy.ndarray.flat() function is used as a 1_D iterator over N-dimensional arrays. It is not a subclass of, Pythonâs built-in iterator object, otherwise it a numpy.flatiter instance. Syntax : numpy.ndarray.flat() Parameters : index : [tuple(int)] index of the values to iterate Return :  1-D i
3 min read
numpy.ndarray.fill() in Python numpy.ndarray.fill() method is used to fill the numpy array with a scalar value. If we have to initialize a numpy array with an identical value then we use numpy.ndarray.fill(). Suppose we have to create a NumPy array a of length n, each element of which is v. Then we use this function as a.fill(v).
2 min read
numpy.ndarray.resize() function - Python numpy.ndarray.resize() function change shape and size of array in-place. Syntax : numpy.ndarray.resize(new_shape, refcheck = True) Parameters : new_shape :[tuple of ints, or n ints] Shape of resized array. refcheck :[bool, optional] If False, reference count will not be checked. Default is True. Ret
1 min read
numpy.ma.filled() function - Python numpy.ma.filled() function return input as an array with masked data replaced by a fill value. If arr is not a MaskedArray, arr itself is returned. If arr is a MaskedArray and fill_value is None, fill_value is set to arr.fill_value. Syntax : numpy.ma.filled(arr, fill_value = None) Parameters : arr :
1 min read
Numpy ndarray.tobytes() function | Python numpy.ndarray.tobytes() function construct Python bytes containing the raw data bytes in the array. Syntax : numpy.ndarray.tobytes(order='C') Parameters : order : [{âCâ, âFâ, None}, optional] Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array. Return : P
1 min read
Numpy recarray.flatten() function | Python In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record array
3 min read
numpy.matrix.A() function - Python numpy.matrix.A() function return self as an ndarray object. Syntax : numpy.matrix.A() Parameters : None Return : [ndarray] Return self as an ndarray. Code #1 : Python3 # Python program explaining # numpy.matrix.A() function # importing numpy as geek import numpy as geek mat = geek.matrix(geek.arange
1 min read
Numpy ndarray.setfield() function | Python numpy.ndarray.setfield() function Put a value into a specified place in a field defined by a data-type. Place val into aâs field defined by dtype and beginning offset bytes into the field. Syntax : numpy.ndarray.setfield(val, dtype, offset=0) Parameters : val : [object] Value to be placed in field.
1 min read
Numpy MaskedArray.compressed() function - Python numpy.MaskedArray.compressed() function return all the non-masked data as a 1-D array. Syntax : numpy.MaskedArray.compressed(self) Return : [ndarray] A new ndarray holding the non-masked data is returned. Code #1 : Python3 # Python program explaining # numpy.MaskedArray.compressed() function # impor
1 min read