How NumPy ndarray.flatten() function in Python can be used?

NumPy ndarray.flatten() function in Python

The ndarray.flatten() function in NumPy is used to return a one-dimensional copy of the array. This method is useful when you want to convert a multi-dimensional array into a single dimension.

Syntax:

ndarray.flatten(order='C')

Parameters

  • order (optional): It specifies the order in which the array elements should be read. The default is ‘C’, which means to read and write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. Other options are:
    • 'F': Fortran-like index order, with the first index changing fastest, and the last index changing slowest.
    • 'A': ‘F’ order if the array is Fortran contiguous, ‘C’ order otherwise.
    • 'K': Keep the order of the array as much as possible.

Returns

  • flattened_array: A one-dimensional array.

Example Usage

Code:

import numpy as np

# Creating a 2D array
arr = np.array([[1, 2], [3, 4]])

# Flattening the array using default C order
flattened_arr = arr.flatten()
print(flattened_arr)
# Output: [1 2 3 4]

# Flattening the array using Fortran order
flattened_arr_f = arr.flatten(order='F')
print(flattened_arr_f)
# Output: [1 3 2 4]

# Creating a 3D array
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

# Flattening the 3D array
flattened_arr_3d = arr_3d.flatten()
print(flattened_arr_3d)

output:

[1 2 3 4 5 6 7 8]

Key Points

  • flatten() always returns a copy of the array.
  • It is different from ravel(), which returns a flattened array but returns a view whenever possible. Use ravel() if you need a flattened view of the array.
  • Choosing the correct order ('C', 'F', 'A', 'K') can be important depending on the structure of your data and performance considerations.

Using ndarray.flatten() can be very useful in situations where you need to process or analyze data in a single-dimensional format, regardless of its original shape.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top