Here are 2 ways to create an empty numpy array:
- Using numpy.empty()
- Using numpy.zeros()
Method 1 :Using numpy.empty()
The np.empty() method creates a new array without initializing its values.
Visual Representation
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
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.
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.