Advanced Reshaping - Creating 3D Arrays
Now let's move on to more advanced reshaping by creating three-dimensional arrays. 3D arrays are essentially arrays of 2D arrays and are useful for representing volumes, time series of images, or other complex data structures.
Add the following code to your numpy_reshape.py
file:
import numpy as np
## Create a simple 1D array
original_array = np.arange(24)
print("Original 1D array:")
print(original_array)
print("Shape of the original array:", original_array.shape)
print("-" * 50) ## Separator line
## Reshape into a 3D array with dimensions 2x3x4
## This creates 2 blocks, each with 3 rows and 4 columns
reshaped_3d = np.reshape(original_array, (2, 3, 4))
print("Reshaped 3D array (2x3x4):")
print(reshaped_3d)
print("Shape of the 3D array:", reshaped_3d.shape)
print("Dimensions of the 3D array:", reshaped_3d.ndim)
print("-" * 50) ## Separator line
## Accessing elements in a 3D array
print("First block of the 3D array:")
print(reshaped_3d[0])
print("\nSecond block of the 3D array:")
print(reshaped_3d[1])
print("\nElement at position [1,2,3] (second block, third row, fourth column):")
print(reshaped_3d[1, 2, 3])
Run your script again:
python3 numpy_reshape.py
The output will show how a 1D array with 24 elements can be transformed into a 3D structure. This structure can be visualized as 2 blocks, each containing a 3ร4 matrix.
Understanding 3D arrays:
- The first dimension (2) represents the number of "blocks" or "layers"
- The second dimension (3) represents the number of rows in each block
- The third dimension (4) represents the number of columns in each row
This structure is particularly useful for image processing (where each "block" might be a color channel), time series data (where each "block" might be a time point), or other scenarios requiring multiple matrices.