.ones()
Published Jun 2, 2025
Contribute to Docs
In NumPy, the .ones()
function creates a new array of the given shape and type, filled with ones.
This function is particularly useful when there is a need to initialize an array with a placeholder value of 1
, which might be multiplied by another value or used in various numerical computations later.
Syntax
numpy.ones(shape, dtype=None, order='C', *, like=None)
Parameters:
shape
(int
or tuple ofint
): Defines the dimensions of the new array.- If an int, a 1-D array of that length is created.
- If a tuple of ints, an array with those dimensions is created (e.g., (2, 3) for a 2x3 array).
dtype
(optional): The desired data type for the array elements. Defaults tofloat64
. Examples:int32
,bool_
,float
.order
: ({‘C’, ‘F’}, optional): Controls whether the array is stored in row-major or column-major memory layout.'C'
(default): Row-major (C-style)'F'
: Column-major (Fortran-style)
like
(array_like, optional): Reference object for creating arrays not strictly of NumPy type. IfNone
, a NumPy array is returned.
Return value:
out
(ndarray): An array of ones of the given shape,dtype
, and order.
Example
This example demonstrates the usage of the .ones()
function:
import numpy as np# Create a 1-D array with 5 ones (default dtype is float64)arr1 = np.ones(5)print("Array 1:\n", arr1)print("Data type of Array 1:", arr1.dtype)print("Shape of Array 1:", arr1.shape)# Create a 2-D array (3 rows, 4 columns) of ones with integer typearr2 = np.ones((3, 4), dtype=int)print("\nArray 2:\n", arr2)print("Data type of Array 2:", arr2.dtype)print("Shape of Array 2:", arr2.shape)# Create a 3-D array of onesarr3 = np.ones((2, 3, 2))print("\nArray 3:\n", arr3)print("Data type of Array 3:", arr3.dtype)print("Shape of Array 3:", arr3.shape)
Here is the output:
Array 1:[1. 1. 1. 1. 1.]Data type of Array 1: float64Shape of Array 1: (5,)Array 2:[[1 1 1 1][1 1 1 1][1 1 1 1]]Data type of Array 2: int64Shape of Array 2: (3, 4)Array 3:[[[1. 1.][1. 1.][1. 1.]][[1. 1.][1. 1.][1. 1.]]]Data type of Array 3: float64Shape of Array 3: (2, 3, 2)
Codebyte Example: Add Bias Term to a Feature Matrix in Machine Learning
In many machine learning algorithms (like linear regression), there is a need to add a bias column of 1s to the input feature matrix. Here’s how numpy.ones()
can be used:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours