w3resource

NumPy: Collapse a 3-D array into one dimension array

NumPy: Array Object Exercise-49 with Solution

Write a NumPy program to collapse a 3-D array into a one-dimensional array.

Pictorial Presentation:

Python NumPy: Collapse a 3-D array into one dimension array

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 3x3 identity matrix using np.eye
x = np.eye(3)

# Printing the original 3x3 identity matrix
print("3-D array:")
print(x)

# Raveling the 3x3 matrix in Fortran (column-major) order to create a one-dimensional array
f = np.ravel(x, order='F')

# Printing the resulting one-dimensional array after raveling
print("One dimension array:")
print(f) 

Sample Output:

3-D array:                                                             
[[ 1.  0.  0.]                                                         
 [ 0.  1.  0.]                                                         
 [ 0.  0.  1.]]                                                        
One dimension array:                                                   
[ 1.  0.  0.  0.  1.  0.  0.  0.  1.]

Explanation:

In the above code -

x = np.eye(3): This part creates a 3x3 identity matrix using the np.eye() function. In an identity matrix, the diagonal elements are 1, and the off-diagonal elements are 0.
f = np.ravel(x, order='F'): The np.ravel() function is used to flatten the input matrix x into a one-dimensional array. The order parameter is set to 'F' (Fortran order), which specifies that the elements should be flattened column-wise (i.e., going down columns first, then moving to the next column).

print(f) prints the resulting one-dimensional NumPy array f, which contains the flattened elements of the identity matrix x in Fortran order.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create an array which looks like below array.
Next: Write a NumPy program to find the 4th element of a specified array.

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://w3resource.com/python-exercises/numpy/python-numpy-exercise-49.php