Numpy zeros

numThe zeros() is a function of Numpy which returns an array of given shape and type filled with zeros.

Syntax:

The syntax of the function numpy.zeros is:

numpy.zeros(shape, dtype = None, order = ‘C’)

shape: Size of the array. The type is integer or sequence of integers.

dtype: It is an optional parameter that specifies the data type of the array. The default value is float.

order: C or F. Default value is C. C stands for C-style and F for FORTRAN-style. It defines how to store the multi-dimensional array, whether in row-major(C-style) or column-major(F-style). row-major means the row-wise operations will be faster and column-major means column-wise operations will be faster.

Examples:

Let’s see some code examples to learn the usage of the function in Python.

Creating 1d array of Numpy zeros:

import numpy

array=numpy.zeros(3)
print(array)
[0. 0. 0. 0. 0.]

Since the default dtype is float. The zeroes 0 are 0. in the returned array.

Multi-dimensional array of Numpy zeros:

import numpy

array=numpy.zeros([3,3])
print(array)
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

With dtype parameter:

import numpy

array=numpy.zeros([3,3],dtype=int)
print(array)
[[0 0 0]
 [0 0 0]
 [0 0 0]]

Manipulating data types:

We can define the elements of numpy array and their respective data type in a tuple format.

import numpy

array=numpy.zeros([3,3],dtype=[('x','int'),('y','float'),('z','int')])
print(array)
[[(0, 0., 0) (0, 0., 0) (0, 0., 0)]
 [(0, 0., 0) (0, 0., 0) (0, 0., 0)]
 [(0, 0., 0) (0, 0., 0) (0, 0., 0)]]

 

 

Translate »