w3resource

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

NumPy: Memory Layout Exercise-3 with Solution

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:

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

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()?

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://www.w3resource.com/python-exercises/numpy/create-and-flatten-a-2d-numpy-array-using-ravel.php