w3resource

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

NumPy: Basic Exercise-56 with Solution

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

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) 

Sample 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:

Previous: NumPy program to create an array of equal shape and data type of a given array.
Next: NumPy program to create a 4x4 array, now create a new array from the said array swapping first and last, second and third columns.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.