w3resource

How to create and flatten a 2D NumPy array using ravel()?


3. 2D Array Flatten with 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.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to flatten a 2D array using ravel() and then compare the result with flatten() to illustrate differences in views and copies.
  • Write a NumPy program to create a 2D array and use ravel() with both 'C' and 'F' order, then compare the flattened outputs.
  • Write a NumPy program to modify the flattened array returned by ravel() and show that the original 2D array reflects these changes.
  • Write a NumPy program to apply ravel() on a sliced section of a 2D array and print both the slice and its flattened version.

Go to:


Previous: How to reshape a 1D array into 2D and print Strides using NumPy?
Next: How to create and reshape a 3D NumPy array using ravel()?

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.