In the NumPy library, we have the capability to generate a variety of specialized arrays. These include arrays filled with zeros, ones, or even uninitialized arrays, among others.
1. Array with zeros:-
NumPy has the zeros() function to create an n-D array.The zeros() function is quite versatile and can be used to create multi dimensional arrays of any size, all initialized to zero.
Example:-
import numpy as np
# Create a 2-D array of size 3x4 filled with zeros
zero_array = np.zeros((3, 4))
print(zero_array)
Output:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
2. Array with ones
Numpy has the ones() function to create an n-D array.The ones() function is very useful when you need to create a multi dimensional array of any size, all initialized to one. Itβs a great tool for initializing weights in machine learning algorithms, among other uses.
import numpy as np
# Create a 2-D array of size 3x4 filled with ones
ones_array = np.ones((3, 4))
print(ones_array)
Output:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
3. Empty array:-
NumPy provides the empty()
function to generate an n-dimensional array. This function differs from the zeros()
function. Specifically, the zeros()
function consistently returns an array filled with zeros of the specified datatype. In contrast, the empty()
function may not necessarily do so.
import numpy as np
# Create a 2-D array of size 3x4 with uninitialized values
empty_array = np.empty((3, 4))
print(empty_array)
[[6.23042070e-307 4.67296746e-307 1.69121096e-306 9.34609111e-307]
[1.33511290e-306 1.33511969e-306 6.23037996e-307 6.23053954e-307]
[9.34609790e-307 8.45593934e-307 9.34600963e-307 1.86921143e-306]]
Please note that the empty() function does not initialize the array elements to any specific values. Therefore, it can sometimes be faster than the zeros() or ones() functions if you are planning to fill the array with data later.
Top comments (0)