w3resource

Flattening a 3x3x3 array to a 1D array using NumPy

NumPy: Advanced Exercise-19 with Solution

Write a NumPy program to create a 3x3x3 array with random values and flatten it to a 1D array.

This task involves generating a 3x3x3 array filled with random values using NumPy and then flattening it into a 1D array. Flattening an array is a common operation in data processing, converting a multi-dimensional array into a single-dimensional array for easier manipulation and analysis.

Sample Solution:

Python Code:

# Importing the necessary NumPy library
import numpy as np

# Create a 3x3x3 array with random values
array = np.random.rand(3, 3, 3)

# Flatten the 3D array to a 1D array
flattened_array = array.flatten()

# Printing the 3D array and its flattened version
print("3x3x3 Array:\n", array)
print("Flattened 1D Array:\n", flattened_array)

Output:

3x3x3 Array:
 [[[0.60776127 0.85659619 0.90421646]
  [0.01376209 0.45704237 0.29651364]
  [0.83378199 0.79445351 0.05627497]]

 [[0.93562363 0.08483905 0.96325464]
  [0.6470311  0.20171087 0.37910202]
  [0.82161452 0.69174066 0.97312358]]

 [[0.52205353 0.38419799 0.17200811]
  [0.04389473 0.49328105 0.47868007]
  [0.30365635 0.94884667 0.74666266]]]
Flattened 1D Array:
 [0.60776127 0.85659619 0.90421646 0.01376209 0.45704237 0.29651364
 0.83378199 0.79445351 0.05627497 0.93562363 0.08483905 0.96325464
 0.6470311  0.20171087 0.37910202 0.82161452 0.69174066 0.97312358
 0.52205353 0.38419799 0.17200811 0.04389473 0.49328105 0.47868007
 0.30365635 0.94884667 0.74666266]

Explanation:

  • Import NumPy library: This step imports the NumPy library, which is essential for numerical operations.
  • Create a 3x3x3 array: We use np.random.rand(3, 3, 3) to generate a 3D array with random values between 0 and 1.
  • Flatten the 3D array to a 1D array: The array.flatten() function transforms the 3D array into a 1D array.
  • Print results: This step prints the original 3D array and its flattened 1D version.

Python-Numpy Code Editor:

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

Previous: Calculate the determinant of a 4x4 random array using NumPy.
Next: Calculate the Trace of a 5x5 random array using NumPy.

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://198.211.115.131/python-exercises/numpy/advanced-numpy-exercise-19.php