w3resource

How to flatten and reshape a 2D NumPy array?

NumPy: Memory Layout Exercise-12 with Solution

Write a NumPy program that creates a 2D array of shape (5, 5) and use ravel() to get a flattened array. Then use reshape() to convert it back to its original shape and print both arrays.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D array of shape (5, 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],
                     [21, 22, 23, 24, 25]])

# Use ravel() to get a flattened array
flattened_array = array_2d.ravel()

# Print the flattened array
print("Flattened array:", flattened_array)

# Use reshape() to convert it back to its original shape
reshaped_array = flattened_array.reshape(5, 5)

# Print the reshaped array
print("Reshaped array:\n", reshaped_array)

Output:

Flattened array: [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 25]
Reshaped array:
 [[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [21 22 23 24 25]]

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 (5, 5) using np.array().
  • Flatten the array: We use the ravel() method to get a flattened 1D array from array_2d, stored in flattened_array.
  • Print the flattened array: We print the flattened_array to see the flattened version of the original array.
  • Reshape to original shape: We use the reshape() method to convert flattened_array back to its original shape (5, 5), resulting in reshaped_array.
  • Print the reshaped array: Finally, we print the reshaped_array to verify it matches the original array's shape.

Python-Numpy Code Editor:

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

Previous: How to change memory layout of a 2D NumPy array to F order?
Next: How to swap axes of a 3D NumPy array?.

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://198.211.115.131/python-exercises/numpy/flatten-and-reshape-a-2d-numpy-array.php