3D Arrays in Python using NumPy

Recently, I was working on a data analysis project where I needed to organize information in three dimensions. While Python lists and NumPy arrays are great for one and two-dimensional data, I realized that 3D arrays offer efficient capabilities for more complex data structures.

In this article, I’ll share several practical ways to create and manipulate 3D arrays in Python, focusing primarily on NumPy which is the gold standard for multidimensional array operations.

We’ll explore everything from basic creation methods to advanced slicing techniques.

3D Arrays in Python

A 3D array is essentially a collection of 2D arrays stacked on top of each other. Think of it as a cube of data with three axes: depth, rows, and columns.

For example, you might use a 3D array to represent:

  • Weather data across multiple cities over time
  • RGB color values in an image
  • Financial data across different companies, metrics, and periods

Read Python Program to Find the Smallest Element in a NumPy Array

Create 3D Arrays in Python

Now, I will explain to you how to create a 3D array in Python by using various methods with suitable examples.

Method 1: Use Python Lists (Nested Lists)

The most basic way to create a 3D array is using nested lists in Python:

# Creating a 3D array (2x3x4) using nested lists
my_3d_array = [
    [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],
    [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]
]

# Accessing elements
print(my_3d_array[0][1][2])

Output:

7

I expected the above example code and added the screenshot below.

3d array in python

While this works, nested lists aren’t optimized for numerical operations and can become unwieldy with larger datasets.

Check out Repeat Arrays N Times in Python NumPy

Method 2: Use NumPy

NumPy provides efficient ways to create and manipulate 3D arrays in Python:

import numpy as np

# Create a 3D array with zeros - great for initializing
zeros_array = np.zeros((2, 3, 4))  # 2 matrices, 3 rows, 4 columns

# Create a 3D array with ones
ones_array = np.ones((2, 3, 4))

# Create a 3D array with random values
random_array = np.random.rand(2, 3, 4)

# Create from nested lists
list_array = np.array([
    [[1, 2], [3, 4]],
    [[5, 6], [7, 8]],
    [[9, 10], [11, 12]]
])

print(f"Shape of array: {list_array.shape}") 

Output:

Shape of array: (3, 2, 2)

I expected the above example code and added the screenshot below.

3d array python

Using NumPy to work with 3D arrays ensures better performance and easier manipulation compared to plain Python lists

Read Python NumPy Not Found: Fix Import Error

Method 3: Create 3D Arrays for Specific Applications

Let’s create a Python 3D array to represent temperature data for major US cities over a week:

import numpy as np

# Temperature data for 5 US cities over 7 days across 3 metrics
# (daily high, daily low, humidity)
cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
metrics = ["High Temp (°F)", "Low Temp (°F)", "Humidity (%)"]

# Create a 3D array with random weather data
weather_data = np.random.randint(50, 100, size=(len(cities), len(days), len(metrics)))

# Access temperature for Chicago on Wednesday (high temp)
chicago_wed_high = weather_data[2, 2, 0]
print(f"Chicago's Wednesday high: {chicago_wed_high}°F")

Output:

Chicago's Wednesday high: 71°F

I expected the above example code and added the screenshot below.

numpy 3d array

This method shows how 3D arrays can effectively organize and analyze real-world multi-dimensional data, such as weather statistics across cities and time.

Check out Create a Matrix in Python

Manipulate 3D Python Arrays

Let me explain to you how to manipulate 3D arrays in Python.

Slicing and Indexing

Slicing 3D arrays follows the same pattern as other arrays, but with three dimensions:

import numpy as np

# Create a sample 3D array
array_3d = np.arange(24).reshape(2, 3, 4)
print("Original 3D array:")
print(array_3d)

# Get a specific 2D array (the first one)
first_matrix = array_3d[0]
print("\nFirst 2D matrix:")
print(first_matrix)

# Get a specific row from a specific 2D array
second_matrix_first_row = array_3d[1, 0]
print("\nFirst row of second matrix:")
print(second_matrix_first_row)

# Get a specific element
specific_element = array_3d[1, 2, 3]
print(f"\nElement at [1,2,3]: {specific_element}")

# Slice across all dimensions
subset = array_3d[0:2, 1:3, 1:3]
print("\nSubset slice across all dimensions:")
print(subset)

Slicing and indexing in 3D arrays allow precise access to subarrays and elements, making data manipulation intuitive and efficient.

Read Random Number Between Two Values in Numpy

Iterate Through 3D Arrays

Iterating through 3D Python arrays in NumPy can be done using traditional nested loops or with efficient built-in tools like np.nditer.

import numpy as np

# Create a small 3D array for demonstration
small_3d = np.arange(8).reshape(2, 2, 2)

# Method 1: Using nested loops
print("Iterating with nested loops:")
for i in range(small_3d.shape[0]):
    for j in range(small_3d.shape[1]):
        for k in range(small_3d.shape[2]):
            print(f"Element at [{i},{j},{k}]: {small_3d[i,j,k]}")

# Method 2: Using nditer
print("\nIterating with nditer:")
for element in np.nditer(small_3d):
    print(element)

Whether you use nested loops for clarity or np.nditer for efficiency, iterating through 3D arrays ensures full access to all elements for processing or analysis.

Check out Create a Python Empty Matrix

Real-World Example: Image Processing with 3D Arrays

One of the most common uses of 3D arrays is working with color images, where each pixel has RGB values:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread

# Load a sample image (make sure you have an image file available)
# Replace 'sample_image.jpg' with your image path
try:
    img = imread('sample_image.jpg')

    # Display image information
    print(f"Image shape: {img.shape}")
    print(f"Number of dimensions: {img.ndim}")

    # Show the original image
    plt.figure(figsize=(10, 5))
    plt.subplot(1, 2, 1)
    plt.imshow(img)
    plt.title("Original Image")

    # Create a red-tinted version by increasing the red channel
    red_tinted = img.copy()
    red_tinted[:, :, 0] = np.clip(red_tinted[:, :, 0] * 1.5, 0, 1)  # Increase red channel

    # Show the modified image
    plt.subplot(1, 2, 2)
    plt.imshow(red_tinted)
    plt.title("Red-Tinted Image")

    plt.tight_layout()
    plt.show()

except FileNotFoundError:
    print("Sample image file not found. Replace with a valid image path.")
except Exception as e:
    print(f"Error: {e}")

Performance Considerations

When working with large 3D arrays, keep these tips in mind:

  1. Use NumPy operations instead of Python loops when possible
  2. Consider data types to save memory (e.g., np.float32 instead of np.float64)
  3. For very large arrays, consider using sparse matrices or libraries like Dask for out-of-memory computation
  4. Vectorize operations for better performance
import numpy as np
import time

# Create a large 3D array
large_array = np.random.rand(100, 100, 100)

# Bad approach (using loops)
start_time = time.time()
result1 = np.zeros_like(large_array)
for i in range(large_array.shape[0]):
    for j in range(large_array.shape[1]):
        for k in range(large_array.shape[2]):
            result1[i,j,k] = large_array[i,j,k] * 2
loop_time = time.time() - start_time

# Good approach (using vectorization)
start_time = time.time()
result2 = large_array * 2
vector_time = time.time() - start_time

print(f"Loop approach time: {loop_time:.4f} seconds")
print(f"Vectorized approach time: {vector_time:.4f} seconds")
print(f"Vectorization is {loop_time/vector_time:.0f}x faster")

Read NumPy Reset Index of an Array in Python

Reshape and Transform 3D Arrays

Sometimes you need to change the shape of your Python 3D array or convert between different dimensionalities:

import numpy as np

# Create a 3D array (2x3x4)
array_3d = np.arange(24).reshape(2, 3, 4)
print("Original 3D array shape:", array_3d.shape)

# Reshape to a different 3D shape
reshaped_3d = array_3d.reshape(4, 2, 3)
print("Reshaped 3D array shape:", reshaped_3d.shape)

# Flatten to 1D
flattened = array_3d.flatten()
print("Flattened array shape:", flattened.shape)

# Convert to 2D (useful for machine learning algorithms)
# Each 2D matrix becomes a row in the new 2D array
to_2d = array_3d.reshape(2, -1)  # 2 rows, automatically calculate columns
print("Converted to 2D shape:", to_2d.shape)

# Convert back to 3D
back_to_3d = to_2d.reshape(2, 3, 4)
print("Back to 3D shape:", back_to_3d.shape)

I hope you found this guide on 3D arrays in Python helpful for your data processing needs.

3D arrays might seem complex at first, but they offer powerful ways to organize and manipulate multidimensional data. Whether you’re working with image processing, scientific simulations, or complex datasets, mastering 3D arrays will significantly expand your Python data capabilities.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.