w3resource

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

NumPy: Memory Layout Exercise-14 with Solution

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.

Python-Numpy Code Editor:

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

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/flatten-a-2d-numpy-array-in-c-and-f-order.php