Skip to main content
Documents
basicsArray CreationArray OperationsArray Computation & AnalysisLinear AlgebraRandom ProbabilityData Input/Output & Conversion

NumPy zeros()

`numpy.zeros` is a function in the NumPy library that creates a new array of given shape and type, filled with zeros. It is widely used for initializing arrays where no initial values are available or needed.

Usage

The `numpy.zeros` function is employed when you need an array of a specific shape initialized with zeros, often as placeholders before performing computations. This function is especially useful for creating arrays for mathematical operations, simulations, or data processing.

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

In this syntax:

  • `shape` specifies the dimensions of the array.
  • `dtype` determines the data type of the array elements (default is `float`).
  • `order` specifies the memory layout, where 'C' is the default for C-style row-major order, and 'F' is for Fortran-style column-major order.

Examples

1. Basic 1D Array

import numpy as np

array_1d = np.zeros(5)

This creates a one-dimensional array with 5 elements, all initialized to zero.

2. 2D Array with Integers

array_2d = np.zeros((3, 4), dtype=int)

Here, a 3x4 two-dimensional array of integers is created, all initialized to zero.

3. Multi-dimensional Array with Custom Order

array_3d = np.zeros((2, 3, 4), order='F')

This example creates a 2x3x4 three-dimensional array with Fortran-style column-major memory order. Note that the `order` parameter can impact performance when accessing elements, especially in large arrays.

Tips and Best Practices

  • Specify the right `dtype`. Choose an appropriate data type to save memory, especially for large arrays.
  • Use for initialization. Ideal for initializing arrays that will be filled with actual data later.
  • Consider memory layout. Use the `order` parameter based on how you plan to access the array elements for performance optimization.
  • Avoid using for small arrays. For very small arrays, the performance gain might be negligible. Consider using direct assignment if clarity is more important.
  • Compare with similar functions. Consider using `numpy.zeros_like` to create an array of zeros with the same shape and type as an existing array, or `numpy.empty` for uninitialized arrays if performance is a priority and zero-initialization is not required.