Open In App

numpy.zeros() in Python

Last Updated : 24 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

numpy.zeros() function creates a new array of specified shapes and types, filled with zeros. It is beneficial when you need a placeholder array to initialize variables or store intermediate results. We can create 1D array using numpy.zeros().

Let's understand with the help of an example:

Python
import numpy as np

#Create 1D array
arr = np.zeros(5)
print(arr)

Output
[0. 0. 0. 0. 0.]

Syntax of numpy.zeros()

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

Parameters:

  • 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.

Return Value

  • numpy.zeros() returns a new array filled with zeros, based on the specified shape and type.

Creating 2D Array

by using NumPy, we can easily create a 2D array filled with zeros using the numpy.zeros() function.

Python
import numpy as np

# Creating a 2D array with 3 rows and 4 columns
arr = np.zeros((3, 4))

print(arr)

Output
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

Specifying Data Type (dtype)

dtype parameter in numpy.zeros() defines the type of data stored in the array.

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)]]

C vs F Order

Choosing the right memory layout can significantly improve performance, depending on our 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

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy