Understanding 2D and 3D Arrays
- A 2D array is a collection of data points arranged in rows and columns, forming a matrix. It can be visualized as a spreadsheet or a grid.
- A 3D array is an extension of a 2D array, where an additional dimension is added, typically representing depth or volume. It can be visualized as a stack of 2D arrays.
Reshaping a 2D Array to 3D using reshape() method
To reshape a 2D NumPy array into a 3D array, you can use the reshape() method. The reshape() method takes two arguments:
- The desired shape of the 3D array as a tuple
- The original 2D array
Example 1
Python3
import numpy as np # Create a 2D array array_2d = np.array([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]) print ( "Original 2D array:" ) print (array_2d) # Reshape the 2D array into a 3D array with shape (3, 3, 1) array_3d = array_2d.reshape(( 3 , 3 , 1 )) print ( "\nReshaped 3D array:" ) print (array_3d) |
Output:
Original 2D array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Reshaped 3D array:
[[[1]
[2]
[3]]
[[4]
[5]
[6]]
[[7]
[8]
[9]]]
In this example, the original 2D array has three rows and three columns. We reshaped it into a 3D array with the shape (3, 3, 1). The resulting 3D array has three 2D slices, each with a shape of (3, 3). The additional dimension (the third dimension) has a size of 1, indicating that each 2D slice has a depth of 1.
Example 2
Python3
import numpy as np # Create a 2D array array_2d = np.array([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ], [ 10 , 11 , 12 ]]) # Reshape the 2D array into a 3D array with shape (2, 2, 3) array_3d = array_2d.reshape(( 2 , 2 , 3 )) print ( "Original 2D array:" ) print (array_2d) print ( "\nReshaped 3D array:" ) print (array_3d) |
Output:
Original 2D array:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Reshaped 3D array:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
The original 2D array is reshaped into a 3D array with a shape of (2, 2, 3).
Numpy Reshape 2D To 3D Array
NumPy is a powerful library in Python used for numerical operations and data analysis. Reshaping arrays is a common operation in NumPy, and it allows you to change the dimensions of an array without changing its data. In this article, we’ll discuss how to reshape a 2D NumPy array into a 3D array.