In this article, we will cover how to create a Numpy array with zeros using Python.
Python Numpy Zeros Array
In Numpy, an array is a collection of elements of the same data type and is indexed by a tuple of positive integers. The number of dimensions in an array is referred to as the array’s rank in Numpy. Arrays in Numpy can be formed in a variety of ways, with different numbers of Ranks dictating the array’s size. It can also be produced from a variety of data types, such as lists, tuples, etc. To create a NumPy array with zeros the numpy.zeros() function is used which returns a new array of given shape and type, with zeros. Below is the syntax of the following method.
Syntax: numpy.zeros(shape, dtype=float, order=’C’)
Parameter:
- shape: integer or sequence of integers
- order: {‘C’, ‘F’}, optional, default: ‘C’
- dtype : [optional, float(byDefault)].
Return: Array of zeros with the given shape, dtype, and order.
Example 1: Creating a one-dimensional array with zeros using numpy.zeros()
import numpy as np
arr = np.zeros( 9 )
print (arr)
|
Output:
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
Example 2: Creating a 2-dimensional array with zeros using numpy.zeros()
import numpy as np
# create a 2-D array of 2 row 3 column arr = np.zeros(( 2 , 3 ))
print (arr)
|
Output:
[[0. 0. 0.] [0. 0. 0.]]
Example 3: Creating a Multi-dimensional array with zeros using numpy.zeros()
import numpy as np
# creating 3D array arr = np.zeros(( 4 , 2 , 3 ))
print (arr)
|
Output:
[[[0. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.]]]
Example 4: NumPy zeros array with an integer data type
import numpy as np
# Creating array of 2 rows 3 column # as Datatype integer arr = np.zeros(( 2 , 3 ), dtype = int )
print (arr)
|
Output:
[[0 0 0] [0 0 0]]
Example 5: NumPy Array with Tuple Data Type and Zeroes
In the output, i4 specifies 4 bytes of integer data type, whereas f8 specifies 8 bytes of float data type.
import numpy as np
# Specifying array as a tuple, and # Specify their data types. arr = np.zeros(( 2 , 2 ), dtype = [( 'x' , 'int' ),
( 'y' , 'float' )])
print (arr)
print (arr.dtype)
|
Output:
[[(0, 0.) (0, 0.)] [(0, 0.) (0, 0.)]] [('x', '<i4'), ('y', '<f8')]