The Wayback Machine - https://web.archive.org/web/20250122184309/https://www.geeksforgeeks.org/numpy-zeros-python/
Open In App

numpy.zeros() in Python

Last Updated : 06 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The numpy.zeros() function returns a new array of given shape and type, with zeros.

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

Parameter:

  • shape: integer or sequence of integers – Defines the shape of the new array. Can be a single integer or a tuple.
  • dtype: optional, default is float – The data type of the returned array. If not specified, the default is float.
  • order: {‘C’, ‘F’} – Specifies the memory layout order:
    • C-order: C-contiguous order means the last index varies the fastest. It is optimal for row-wise operations.
    • F-order: FORTRAN-contiguous order means the first index varies the fastest. It is optimal for column-wise operations.

The function returns a Numpy ndarray filled with zeros of the specified shape, data type, and memory order.

Example 1: Creating Arrays of Zeros

Let’s begin with a basic example where we create arrays filled with zeros.

Python
import numpy as np

# Create a 2x2 array of zeros
b = np.zeros((2, 2))
print("Matrix b:", b)

# Create a 3x3 array of zeros
a = np.zeros((3, 3))
print("Matrix a:", a)

# Create a 3x3 array of zeros with float data type
c = np.zeros((3, 3), dtype=float)
print("Matrix c:", c)

Output
('Matrix b:', array([[0., 0.],
       [0., 0.]]))
('Matrix a:', array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]]))
('Matrix c:', array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0.,...

This example demonstrates how to create different shapes of arrays filled with zeros. The arrays have a default data type of float.

Example 2: Manipulating Data Types

You can also specify the data type when creating the array. Let’s see how to set it to a tuple of mixed types.

Python
import numpy as np 
# Create an array of tuples with zeros
d = np.zeros((2, 2), dtype=[('f', 'f4'), ('i', 'i4')])
print(d)

Output
[[(0., 0) (0., 0)]
 [(0., 0) (0., 0)]]

In this example, the array elements are initialized as tuples, where the first element is a float and the second is an integer.

Memory Layout: C vs F Order

Choosing the right memory layout can significantly improve performance, depending on your specific operations. If your operations are row-wise, use C-order. If they are column-wise, use F-order.

Python
import numpy as np 
# Create a 2x3 array in C-order
e = np.zeros((2, 3), order='C')
print("C-order array:", e)

# Create a 2x3 array in F-order
f = np.zeros((2, 3), order='F')
print("F-order array:", f)

Output
C-order array: [[0. 0. 0.]
 [0. 0. 0.]]
F-order array: [[0. 0. 0.]
 [0. 0. 0.]]



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg