w3resource

NumPy: Create a three-dimension array with shape (3,5,4) and set to a variable


Create 3D Array of Shape (3,5,4)

Write a NumPy program to create a three-dimensional array with the shape (3,5,4) and set it to a variable.

This problem involves writing a NumPy program to create a three-dimensional array with the shape (3, 5, 4) and assigning it to a variable. The task requires utilizing NumPy's array creation capabilities to efficiently generate the array with the specified shape. By assigning the array to a variable, the program enables easy access and manipulation of the three-dimensional data structure for various computational and analytical tasks.

Sample Solution:

Python Code:

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

# Creating a NumPy array 'nums' containing a 3x5x4 multi-dimensional array
nums = np.array([[[1, 5, 2, 1],
               [4, 3, 5, 6],
               [6, 3, 0, 6],
               [7, 3, 5, 0],
               [2, 3, 3, 5]],
              
              [[2, 2, 3, 1],
               [4, 0, 0, 5],
               [6, 3, 2, 1],
               [5, 1, 0, 0],               
               [0, 1, 9, 1]],
              
              [[3, 1, 4, 2],
               [4, 1, 6, 0],
               [1, 2, 0, 6],
               [8, 3, 4, 0],               
               [2, 0, 2, 8]]]) 

# Printing a message indicating the array 'nums'
print("Array:")
print(nums) 

Output:

Array:
[[[1 5 2 1]
  [4 3 5 6]
  [6 3 0 6]
  [7 3 5 0]
  [2 3 3 5]]

 [[2 2 3 1]
  [4 0 0 5]
  [6 3 2 1]
  [5 1 0 0]
  [0 1 9 1]]

 [[3 1 4 2]
  [4 1 6 0]
  [1 2 0 6]
  [8 3 4 0]
  [2 0 2 8]]]

Explanation:

The above code shows the creation of a 3-dimensional NumPy array with given values and prints it:

nums = np.array([...]) statement creates a 3-dimensional NumPy array of shape (3, 5, 4) and stores in a variable ‘nums’. The outermost dimension has 3 elements (matrices), each having 5 rows and 4 columns.

print(nums): Prints the created 3-dimensional array.

Python-Numpy Code Editor: