Shape- and dtype-compatible initialization
Allocate a zero buffer matching an existing tensor or ndarray.
NumPy · Function
Creates a new array filled with zeros, using an input array-like object's shape and data type by default. Optional arguments can override the dtype, layout, subclass handling, shape, or device.
numpy.zeros_like builds a new zero-filled array using the input's shape and data type by default. Optional arguments can change the output dtype, memory order, subclass behavior, shape, and device.
numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None, like=None)| Name | Type | Description |
|---|---|---|
a | array_like | Array-like object whose shape and data type provide the defaults for the result. |
dtype | data-type, optional | Output data type; if omitted, the type is inferred from a. |
order | {'C', 'F', 'A', or 'K'}, optional | Memory layout of the result: 'C', 'F', 'A', or 'K'. |
subok | bool, optional | If true, preserve an input ndarray subclass; otherwise return a base ndarray. |
shape | int or sequence of ints, optional | Shape of the result. If omitted, the shape of a is used. |
device | str, optional | Device on which to place the result; relevant to array-API-compatible creation. |
like | array_like, optional | Array-API-compatible namespace used for array creation. |
An ndarray filled with zeros, using the requested or inferred shape, data type, memory order, subclass behavior, and device.
import numpy as np
values = np.arange(6, dtype=np.float32).reshape(2, 3)
zeros = np.zeros_like(values)
print(zeros)
print(zeros.dtype) # float32Creates a zero-filled array matching values in shape and dtype.
Allocate a zero buffer matching an existing tensor or ndarray.
Prepare a same-sized accumulator before numerical processing.
Create a placeholder that follows a chosen memory layout or dtype.
It returns a zero-filled array whose shape and data type are taken from a supplied array-like object. The returned array is newly created rather than a view of the input.
Follow-up: How would you force a different element type? Pass dtype, such as dtype=np.float64; this overrides the input type.
The default dtype is inferred from a, while an explicit dtype overrides that inference. This lets the function preserve an existing numeric type or deliberately choose another one.
Follow-up: What happens with a complex input and dtype=float? The result uses float, so complex information is not represented in the output dtype.
order controls the result's memory layout using C, F, A, or K. The default K attempts to match the input's layout as closely as possible.
Follow-up: When might shape matter? Supplying shape changes the output dimensions; if omitted, the input shape is used.
numpy.ones_likenumpy.full_likenumpy.empty_likenumpy.zeros