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.


For more Practice: Solve these Related Problems:

  • Construct a 3D array of shape (3,5,4) filled with sequential integers and then reverse the order of its 2D subarrays.
  • Create a 3D array of the specified shape using random values and compute the cumulative sum along the third axis.
  • Generate a 3D array of shape (3,5,4) and reshape it into a 2D array with dimensions (3,20) while preserving element order.
  • Build a 3D array of shape (3,5,4) where each slice along the first axis is filled with a constant value derived from the slice index squared.

Go to:


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.

Python-Numpy Code Editor:

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.