numpy.zeros() in Python (original) (raw)

Last Updated : 24 Jan, 2025

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)

`

Table of Content

**Syntax of numpy.zeros()

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

**Parameters:

Return Value

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

Similar Reads

Introduction







Creating NumPy Array













NumPy Array Manipulation


















Matrix in NumPy


















Operations on NumPy Array




Reshaping NumPy Array















Indexing NumPy Array






Arithmetic operations on NumPyArray










Linear Algebra in NumPy Array