How to create a three-dimensional array using NumPy? How to create a 3-dimensional array using NumPy?
To create a three-dimensional array using NumPy, you can use the numpy.array
function with nested lists. Each nested list represents a 2D matrix or a set of 2D matrices, which combine to form a 3D array. Here is an example code snippet that demonstrates how to create a three-dimensional array with NumPy:
import numpy as np
# Create a three-dimensional array with 2 matrices of size 3x3
arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
[[10, 11, 12], [13, 14, 15], [16, 17, 18]]])
print(arr)
In this example, we imported the NumPy library using the import
statement, and then we used the numpy.array
function to create a three-dimensional array with 2 matrices of size 3x3. We passed in a list of two nested lists, each containing three nested lists of three integers. We assigned the resulting array to the variable arr
. Finally, we printed the contents of the array using the print
statement.
You can create a three-dimensional array using NumPy in many other ways, such as using the numpy.zeros
function or the numpy.random.rand
function, depending on your needs.
Comments
Post a Comment