numpy
  1. numpy-numpyzeros

numpy.zeros()

The numpy.zeros() function is used to create a new array filled with zeros. This function is a commonly used NumPy function, particularly when initializing a new array of a certain size.

Syntax

The basic syntax of the numpy.zeros() function is as follows:

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

Here, shape is an integer or a tuple of integers that represents the shape of the array. dtype is an optional data type for the array, which defaults to float. order is the order in which the array is stored, either 'C' for row-major order or 'F' for column-major order.

Example

Consider the following example, where we create a new NumPy array of size 4x3 filled with zeros:

import numpy as np

arr = np.zeros((4, 3))

print(arr)

Output:

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

Here, np.zeros((4,3)) creates a new array with shape (4,3) and fills it with zeros. The resulting array is printed to the console.

Explanation

The numpy.zeros() function creates a new array with a specified shape and fills it with zeros. The function is equivalent to creating an array with the specified shape and filling it with zeros manually.

Use

The numpy.zeros() function is commonly used when we need to initialize a new array of a specific shape. This can be useful in various data science applications like machine learning, computer vision, and numerical analysis.

Important Points

  • The dtype argument of the numpy.zeros() function specifies the data type of the array. For example, dtype=int64 will create an array of type int64.
  • The order argument specifies the order in which the array is stored in memory. order='C' (the default) creates a row-major array, while order='F' creates a column-major array.

Summary

The numpy.zeros() function creates a new array filled with zeros with a specified shape and data type. The function is commonly used to initialize new arrays in data science applications. It is simple to use and can help simplify array initialization.

Published on: