How to Create an Empty Numpy Array

Here are 2 ways to create an empty numpy array:

  1. Using numpy.empty()
  2. Using numpy.zeros()

Method 1 :Using numpy.empty()

The np.empty() method creates a new array without initializing its values.

Visual Representation

Visual Representation of Create an Empty Numpy Array using numpy.empty()

Example

import numpy as np

# Creates a 3x2 empty array
empty_array = np.empty((3, 2))

#Print the array with float values
print("3x2 float matrix: ", empty_array)

# Create and print another 3x2 empty array with integer data type 
print("3x2 int matrix: ",np.empty((3, 2),dtype=int))

Output

3x2 float matrix: 
[[ 6.06338704e-317 0.00000000e+000]
 [ 1.15150043e-310 1.15150043e-310]
 [-7.25640221e+023 1.15150043e-310]]

3x2 int matrix: 
[[ 12272432 0]
 [ 23306628212720 23306628222256]
 [-4259502406166423405 23306628213232]]

Method 2: Using numpy.zeros()

The np.zeros() method creates a new array where all elements are initialized to zero.

Visual Representation

Visual Representation of Using numpy.zeros()

Example

import numpy as np

# Creates a 3x2 empty array
empty_array = np.zeros((3, 2))

print("3x2 float matrix: ", empty_array)

print("3x2 int matrix: ",np.zeros((3, 2),dtype=int))

Output

3x2 float matrix: 
[[0. 0.]
 [0. 0.]
 [0. 0.]]

3x2 int matrix: 
[[0 0]
 [0 0]
 [0 0]]

The numpy.empty() method can be marginally faster than numpy.zeros() as it does not initialize the array values to zero.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.