numpy.zeros() is used to create a NumPy array of a specified shape where all elements are initialized to 0. It is commonly used when you need an array with default values before performing calculations or storing data.
Example: The following example creates a 1D array containing 5 zeros.
import numpy as np
arr = np.zeros(5)
print(arr)
Output
[0. 0. 0. 0. 0.]
Explanation: np.zeros(5) creates a one-dimensional array with 5 elements and each element is initialized to 0.
Syntax
numpy.zeros(shape, dtype=float, order='C')
Parameters:
- shape: Integer or tuple specifying the size of the array.
- dtype (optional): Data type of array elements. Default is float.
- order (optional): Memory layout of the array. 'C' for row-major order and 'F' for column-major order.
Examples
Example 1: This example creates a 2D array with 3 rows and 4 columns. All elements are initialized to zero.
import numpy as np
arr = np.zeros((3, 4))
print(arr)
Output
[[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]
Explanation: np.zeros((3, 4)) creates a 2D array with 3 rows and 4 columns filled with 0.
Example 2: This example creates a zero-filled array with integer values instead of the default floating-point values.
import numpy as np
arr = np.zeros((2, 3), dtype=int)
print(arr)
Output
[[0 0 0] [0 0 0]]
Explanation: dtype=int argument makes np.zeros() create an array of integers rather than floats.
Example 3: This example creates a 3D array with 2 blocks, each containing 2 rows and 3 columns.
import numpy as np
arr = np.zeros((2, 2, 3))
print(arr)
Output
[[[0. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.]]]
Explanation: np.zeros((2, 2, 3)) creates a three-dimensional array where all elements are initialized to 0.