w3resource

How to flatten a 2D NumPy array in 'C' and 'F' order?


14. 2D Array Flatten Order Comparison

Write a NumPy program that creates a 2D array of shape (4, 5) and use flatten(order='C') and flatten(order='F'). Print both flattened arrays.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D array of shape (4, 5)
array_2d = np.array([[1, 2, 3, 4, 5],
                     [6, 7, 8, 9, 10],
                     [11, 12, 13, 14, 15],
                     [16, 17, 18, 19, 20]])

# Flatten the array in row-major ('C') order
flattened_c = array_2d.flatten(order='C')

# Print the flattened array in 'C' order
print("Flattened array in 'C' order:", flattened_c)

# Flatten the array in column-major ('F') order
flattened_f = array_2d.flatten(order='F')

# Print the flattened array in 'F' order
print("Flattened array in 'F' order:", flattened_f)

Output:

Flattened array in 'C' order: [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]
Flattened array in 'F' order: [ 1  6 11 16  2  7 12 17  3  8 13 18  4  9 14 19  5 10 15 20]

Explanation:

  • Import NumPy library: We start by importing the NumPy library to handle array operations.
  • Create a 2D array: We create a 2D array array_2d of shape (4, 5) using np.array().
  • Flatten in 'C' order: We use the flatten(order='C') method to flatten array_2d in row-major order (C-style), resulting in flattened_c.
  • Print the 'C' order array: We print flattened_c to display the flattened array in 'C' order.
  • Flatten in 'F' order: We use the flatten(order='F') method to flatten array_2d in column-major order (Fortran-style), resulting in flattened_f.
  • Print the 'F' order array: We print flattened_f to display the flattened array in 'F' order.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to flatten a non-square 2D array using flatten(order='C') and flatten(order='F') and compare key elements.
  • Write a NumPy program to verify that flatten() returns a copy by modifying the flattened array and ensuring the original remains unchanged.
  • Write a NumPy program to apply flatten() on a sliced 2D array in both 'C' and 'F' orders and compare the outputs.
  • Write a NumPy program to demonstrate the difference in flattened output when using different orders on a 2D array with irregular dimensions.

Go to:


Previous: How to swap axes of a 3D NumPy array?
Next: How to transpose a 2D NumPy array and print strides?.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.