Hello and welcome to this tutorial on Numpy zeros. In this tutorial, we will be learning about the NumPy zeros method and also seeing a lot of examples regarding the same. So let us begin!
Also read: NumPy Interview Questions: Prepare Yourself For Your Python Job Interview
What is NumPy zeros?
NumPy zeros
method returns a Numpy array of the given shape and data type with all values set to 0.
Syntax of NumPy zeros
Let us have a look at the syntax first.
numpy.zeros(shape, dtype=float, order='C', like=None)
Parameter | Description | Required/Optional |
shape | The desired shape of the array. It can be an int or a tuple of ints. | Required |
dtype | The desired data type of the array. The default data type is float. | Optional |
order | The desired order in which the multi-dimensional data is to be stored in the memory. It can either be row-major (‘C’) or column-major (‘F’). The default order is ‘C’ i.e. row-major. | Optional |
like (array_like) | Reference object to allow the creation of arrays that are not NumPy arrays. | Optional |
Returns: An array with the given shape, data type and order.
Examples of using Numpy Zeros
Let’s now look at some practical examples of the numpy.zeros() method.
1-dimensional array using zeros
import numpy as np
one_dim_array = np.zeros(4)
print(one_dim_array)
Output:
[0. 0. 0. 0.]
2-dimensional array using zeros
N x M array
import numpy as np
two_dim_array = np.zeros((2, 3))
print(two_dim_array)
Output:
[[0. 0. 0.]
[0. 0. 0.]]
1 x N array
import numpy as np
one_row_array = np.zeros((1, 4))
print(one_row_array)
Output:
[[0. 0. 0. 0.]]
N x 1 array
import numpy as np
one_col_array = np.zeros((4, 1))
print(one_col_array)
[[0.]
[0.]
[0.]
[0.]]
1-dimensional int-type array
import numpy as np
one_dim_int_array = np.zeros(3, dtype=np.int64)
print(one_dim_int_array)
Output:
[0 0 0]
2-dimensional int-type array
import numpy as np
two_dim_int_array = np.zeros((2, 4), dtype=np.int64)
print(two_dim_int_array)
Output:
[[0 0 0 0]
[0 0 0 0]]
1-dimensional custom data type array
import numpy as np
custom_one_dim_array = np.zeros(3, dtype=[('x', 'int'), ('y', 'float')])
print(custom_one_dim_array)
print(custom_one_dim_array.dtype)
Output:
[(0, 0.) (0, 0.) (0, 0.)]
[('x', '<i4'), ('y', '<f8')]
In this example, we specified the first value to be an int and the second one to be float.
2-dimensional custom data type array
We can specify the elements of the array as a tuple and also specify their data types.
import numpy as np
custom_two_dim_array = np.zeros((3, 2), dtype=[('x', 'float'), ('y', 'int')])
print(custom_two_dim_array)
print(custom_two_dim_array.dtype)
Output:
[[(0., 0) (0., 0)]
[(0., 0) (0., 0)]
[(0., 0) (0., 0)]]
[('x', '<f8'), ('y', '<i4')]
Here, the code specifies the first value of the tuple in the array elements be a float and the second one be an int.
Conclusion
That’s all! In this tutorial, we learned about the Numpy zeros method and practiced different types of examples using the same.