Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

NumPy: ones() function

ones() function

The ones() function is used to get a new array of given shape and type, filled with ones.

Syntax:

numpy.ones(shape, dtype=None, order='C')
NumPy array: ones() function

Version: 1.15.0

Parameter:

Name Description Required /
Optional
shape Shape of the new array, e.g., (2, 3) or 2. Required
dtype The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64. optional
order Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory optional

Return value:

[ndarray] Array of ones with the given shape, dtype, and order.

Example-1: numpy.ones()

>>> import numpy as np
>>> np.ones(7)
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.])
>>> np.ones((2, 1))
array([[ 1.],
       [ 1.]])
>>> np.ones(7,)
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.])
>>> x = (2, 3)
>>> np.ones(x)
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>>

Pictorial Presentation:

NumPy array: ones() function
NumPy array: ones() function

Example-2: numpy.ones() where data type is float

>>> import numpy as np
>>> np.ones((2,2)) #default datatype float
array([[ 1.,  1.],
       [ 1.,  1.]])
>>> np.ones((2,2), dtype=int)
array([[1, 1],
       [1, 1]])
>>> 

Python - NumPy Code Editor:

Previous: identity()
Next: ones_like()