w3resource

How to flatten and reshape a 2D NumPy array?


12. 2D Array Ravel and Reshape Back

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.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to flatten a 2D array with ravel() and then reshape it into a different valid shape while verifying data integrity.
  • Write a NumPy program to demonstrate that changes in a ravelled view affect the original 2D array by reshaping back and comparing.
  • Write a NumPy program to flatten a 2D array using ravel() in both C and Fortran orders, then reshape each back to 2D and compare the results.
  • Write a NumPy program to flatten a 2D array using ravel(), perform an arithmetic operation on the flattened array, and reshape it back to the original shape.

Go to:


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

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.