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.
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:
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.
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/basic/numpy-basic-exercise-56.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics