How to create and flatten a 2D NumPy array using ravel()?
Write a NumPy program to create a 2D array of shape (4, 4), then use ravel() to flatten it and print the result.
Sample Solution:
Python Code:
import numpy as np
# Create a 2D array of shape (4, 4)
array_2d = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
# Use ravel() to flatten the 2D array
flattened_array = array_2d.ravel()
# Print the flattened array
print(flattened_array)
Output:
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
Explanation:
- Import NumPy library: We start by importing the NumPy library which provides support for large multi-dimensional arrays and matrices.
- Create a 2D array: We create a 2D array array_2d of shape (4, 4) using np.array().
- Flatten the array: We use the ravel() method to flatten array_2d into a 1D array, stored in flattened_array.
- Print the result: Finally, we print the flattened array.
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