Create 3D Array in NumPy


NumPy - Create 3D Array

To create a 3D (3 dimensional) array in Python using NumPy library, we can use any of the following methods.

  • numpy.array() - Creates array from given values.
  • numpy.zeros() - Creates array of zeros.
  • numpy.ones() - Creates array of ones.
  • numpy.empty() - Creates an empty array.

1. Create 3D Array using numpy.array()

Pass a nested list (list of lists of lists) to numpy.array() function.

In the following program, we create a numpy 3D array of shape (2, 3, 4).

Python Program

import numpy as np

# create a 3D array with shape (2, 3, 4)
nested_list = [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],
               [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]
arr = np.array(nested_list)

print(arr)

Output

[[[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]]

 [[13 14 15 16]
  [17 18 19 20]
  [21 22 23 24]]]

2. Create 3D Array using numpy.zeros()

Pass shape of the required 2D array, as a tuple, as argument to numpy.zeros() function. The function returns a numpy array with specified shape, and all elements in the array initialised to zeros.

Python Program

import numpy as np

# create a 3D array with shape (2, 3, 4)
shape = (2, 3, 4)
arr = np.zeros(shape)

print(arr)

Output

[[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]

3. Create 3D Array using numpy.ones()

Pass shape of the required 3D array, as a tuple, as argument to numpy.ones() function. The function returns a numpy array with specified shape, and all elements in the array initialised to ones.

Python Program

import numpy as np

# create a 3D array with shape (2, 3, 4)
shape = (2, 3, 4)
arr = np.ones(shape)

print(arr)

Output

[[[1. 1. 1. 1.]
  [1. 1. 1. 1.]
  [1. 1. 1. 1.]]

 [[1. 1. 1. 1.]
  [1. 1. 1. 1.]
  [1. 1. 1. 1.]]]

4. Create 3D Array using numpy.empty()

Pass shape of the required 3D array, as a tuple, as argument to numpy.empty() function. The function returns a numpy array with specified shape.

Python Program

import numpy as np

# create a 3D array with shape (2, 3, 4)
shape = (2, 3, 4)
arr = np.empty(shape)

print(arr)

Output

[[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]

Summary

In this NumPy Tutorial, we learned how to create a 3D numpy array in Python using different NumPy functions.