Preallocate a uniform array
Initialize weights, masks, counters, or other numeric buffers before computation.
NumPy · Function
Creates a new NumPy array of a specified shape, filled with ones. By default it uses float64 values; dtype and memory order can be selected.
Call np.ones with either separate dimension arguments or a tuple of dimensions. It allocates and returns a new ndarray, fills every element with one, uses float64 unless dtype is specified, and can control multidimensional memory layout with order.
numpy.ones(shape, dtype=None, order='C', *, device=None, like=None)| Name | Type | Description |
|---|---|---|
shape | int or sequence of ints | Dimensions of the new array, given as an integer or sequence of integers. |
dtype | data-type, optional | Element data type; defaults to numpy.float64. |
order | {'C', 'F'}, optional | Memory layout for multidimensional arrays: C or F; defaults to C. |
like | array_like, optional | Optional object implementing the array protocol; the returned array is created through that protocol. |
An ndarray containing ones with the requested shape and dtype.
import numpy as np
weights = np.ones((2, 3), dtype=np.float32)
print(weights)
Creates a 2×3 floating-point array whose six elements are initialized to 1.
Initialize weights, masks, counters, or other numeric buffers before computation.
Create integer-valued dimensions or indicator data.
Prepare arrays for libraries that expect a specific multidimensional memory layout.
np.ones creates a new array with the requested shape and fills it with ones. Its default dtype is numpy.float64, so integer output requires an explicit dtype such as int.
Follow-up: How would you create a 2-by-3 integer array? Pass (2, 3) as the shape and dtype=int.
The shape can be one integer for a one-dimensional array or a sequence of integers for multiple dimensions. For example, np.ones(5) has shape (5,), while np.ones((2, 3)) has two dimensions.
Follow-up: What shape argument creates a three-dimensional array with dimensions 2, 4, and 5? Use (2, 4, 5).
order accepts C or F and controls how multidimensional data is stored in memory. C selects row-major storage, while F selects column-major storage.
Follow-up: When is order especially relevant? When interoperating with code that expects a particular memory layout or optimizing multidimensional array access.
numpy.zerosnumpy.emptynumpy.fullnumpy.ones_likenumpy.asarray