How to flatten and reshape a 2D NumPy array?
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics