Shape- and dtype-compatible initialization
Allocate an array matching an existing tensor or ndarray before accumulation or masking.
NumPy · Function
Creates an array filled with ones, using a supplied array-like object to determine the default shape and data type. Optional arguments can change the dtype, memory order, subclass handling, shape, or device.
Pass an array-like reference to produce a new array filled with ones. By default, the result follows the reference's shape, data type, and suitable memory layout; optional arguments can override the type, layout, subclass behavior, shape, or device.
numpy.ones_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None)| Name | Type | Description |
|---|---|---|
a | array_like | Reference array-like object whose shape and data type provide the defaults for the result. |
dtype | data-type, optional | Replacement data type for the result. |
order | {'C', 'F', 'A', or 'K'}, optional | Requested memory layout: 'C', 'F', 'A', or 'K'. |
subok | bool, optional | Whether to preserve the input array subclass. |
shape | int or tuple of ints, optional | Replacement output shape. |
device | str, optional | Device on which to place the result; the documentation lists this as an Array-API interoperability option. |
out — ndarray: An array of ones with the same shape and type as a, unless overridden by the optional arguments.
import numpy as np
x = np.arange(6, dtype=np.float64).reshape(2, 3)
y = np.ones_like(x)
print(y)
print(y.dtype)Creates a 2×3 floating-point array filled with ones, preserving the input shape and data type.
Allocate an array matching an existing tensor or ndarray before accumulation or masking.
Build test fixtures or expected-value arrays without manually repeating dimensions.
Create a same-layout working buffer while optionally selecting a different dtype or shape.
It creates and returns an array containing ones. The reference argument supplies the default shape and data type, while dtype, order, subok, shape, and device can customize the result.
Follow-up: How would you guarantee floating-point output from an integer reference? Pass dtype=float or another floating-point dtype explicitly.
The default dtype is inherited from the reference array, but the dtype argument overrides it. Thus, an integer input normally yields integer ones, whereas dtype=np.float32 yields single-precision ones.
Follow-up: What happens when dtype and shape are both specified? The result uses the requested dtype and requested shape independently of the reference's corresponding attributes.
order controls the output memory layout using C, F, A, or K. The default K attempts to preserve the input's layout characteristics, subject to the implementation's layout rules.
Follow-up: When would shape be useful? It allows a new shape to be requested while still using the reference for other defaults such as dtype.
numpy.empty_likenumpy.zeros_likenumpy.full_like