0
0
NumpyHow-ToBeginner ยท 3 min read

How to Create a 3D Array in NumPy: Simple Guide

You can create a 3D array in NumPy by passing a list of lists of lists to np.array(). This creates an array with three dimensions representing depth, rows, and columns.
๐Ÿ“

Syntax

To create a 3D array, use np.array() with nested lists. The outer list represents the depth (number of 2D arrays), each inner list represents rows, and the innermost lists represent columns.

  • np.array(data): Converts nested lists into a NumPy array.
  • data: A list of lists of lists for 3D structure.
python
import numpy as np

array_3d = np.array([
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]]
])
๐Ÿ’ป

Example

This example creates a 3D array with 2 layers, each containing 2 rows and 3 columns. It then prints the array and its shape to show the dimensions.

python
import numpy as np

array_3d = np.array([
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]]
])

print("3D Array:")
print(array_3d)
print("Shape of array:", array_3d.shape)
Output
3D Array: [[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]] Shape of array: (2, 2, 3)
โš ๏ธ

Common Pitfalls

Common mistakes when creating 3D arrays include:

  • Using uneven inner lists, which causes NumPy to create an array of objects instead of a numeric 3D array.
  • Confusing the order of dimensions (depth, rows, columns).

Always ensure all inner lists have the same length to form a proper 3D array.

python
import numpy as np

# Wrong: uneven inner lists
wrong_array = np.array([
    [[1, 2], [3, 4, 5]],  # second inner list has 3 elements
    [[6, 7], [8, 9]]
])

print("Wrong array type:", wrong_array.dtype)

# Right: all inner lists have same length
right_array = np.array([
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]]
])

print("Right array type:", right_array.dtype)
Output
Wrong array type: object Right array type: int64
๐Ÿ“Š

Quick Reference

ConceptDescriptionExample
Create 3D arrayUse np.array() with nested listsnp.array([[[1]]])
ShapeReturns (depth, rows, columns)array.shape
Access elementUse three indices: depth, row, columnarray[0, 1, 2]
Check typeEnsure numeric dtype, not objectarray.dtype
โœ…

Key Takeaways

Create a 3D array by passing nested lists to np.array().
Ensure all inner lists have the same length to avoid object arrays.
The shape of a 3D array is (depth, rows, columns).
Access elements using three indices: depth, row, and column.
Check the array's dtype to confirm it is numeric, not object.