Python NumPy - Flatten 3D Array into 1D Array

By IncludeHelp Last updated : September 11, 2024

Problem Statement

Given a 3D NumPy array of shape (3, 4, 5), and write Python code to flatten this array in such a way that it becomes a linear 1D array of length = 3x4x5

Flattening 3D Array into 1D Array

To flatten a 3D NumPy array into a 1D NumPy array, use the numpy.ravel() function which is used to return a contiguous flattened array. It gives us a 1-D array, containing the elements of the input.

Python Code to Flatten 3D Array into 1D Array

Let us understand with the help of an example:

# Importing numpy
import numpy as np

# Creating an array
arr = np.arange(60).reshape((3, 4, 5))

# Display original array
print("Original Array:\n",arr,"\n")

# Flattening array
res = np.ravel(arr)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Original Array:
 [[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]
  [15 16 17 18 19]]

 [[20 21 22 23 24]
  [25 26 27 28 29]
  [30 31 32 33 34]
  [35 36 37 38 39]]

 [[40 41 42 43 44]
  [45 46 47 48 49]
  [50 51 52 53 54]
  [55 56 57 58 59]]] 

Result:
 [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 
54 55 56 57 58 59]

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.