numpy
  1. numpy-numpyndarrayflatten

numpy.ndarray.flatten()

The numpy.ndarray.flatten() function in NumPy returns a copy of the array in one dimension (i.e., flattened array). It collapses multidimensional arrays into one dimension, row by row.

Syntax

The syntax for using numpy.ndarray.flatten() is as follows:

numpy.ndarray.flatten(order='C')

Here, order is an optional parameter that specifies the order in which the indices are read in the input array.

Example

Consider the following example:

import numpy as np

arr = np.array([[1, 2], [3, 4]])
print("Original Array:")
print(arr)

flattened_arr = arr.flatten()
print("Flattened Array:")
print(flattened_arr)

Output:

Original Array:
[[1 2]
 [3 4]]
Flattened Array:
[1 2 3 4]

In this example, a 2D array is first created using the np.array() function. The numpy.ndarray.flatten() function is then applied to the array, resulting in a flattened array as output.

Explanation

The numpy.ndarray.flatten() function returns a copy of the input array in one dimension. It collapses multidimensional arrays into one dimension, row by row. The order parameter in this function specifies the way the indices are read in the input array. The default is "C" order, which means row-major order.

Use

The numpy.ndarray.flatten() function is useful when working with multi-dimensional arrays, where the data needs to be flattened before processing.

Important Points

  • The output of numpy.ndarray.flatten() is a one-dimensional array.
  • The input array is not modified by this function.
  • The order parameter in this function specifies the way the indices are read in the input array. The default is "C" order, which means row-major order.

Summary

The numpy.ndarray.flatten() function in NumPy returns a copy of the input array in one dimension (i.e., flattened array). It collapses multidimensional arrays into one dimension, row by row. This function can be useful when working with multi-dimensional arrays, where the data needs to be flattened before processing. The order parameter in this function specifies the way the indices are read in the input array, and the default is "C" order (row-major order).

Published on: