NumPy: ones_like() function

ones_like() function

The ones_like() function is used to get an array of ones with the same shape and type as a given array.


numpy.ones_like(a, dtype=None, order='K', subok=True)
NumPy array: ones_like() function

Version: 1.15.0


Name Description Required /
a The shape and data-type of a define these same attributes of the returned array Required
dtype Overrides the data type of the result. New in version 1.6.0. optional
order Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if a is Fortran contiguous, 'C' otherwise. 'K' means match the layout of a as closely as possible. optional
subok If True, then the newly created array will use the sub-class type of ‘a’, otherwise it will be a base-class array. Defaults to True. optional

Return value:

[ndarray] Array of ones with the same shape and type as a.

Example: numpy.ones_like() function

>>> import numpy as np
>>> x = np.arange(4)
>>> x = x.reshape((2,2))
>>> x
array([[0, 1],
       [2, 3]])
>>> x = np.arange(6)
>>> x = x.reshape((2,3))
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.ones_like(x)
array([[1, 1, 1],
       [1, 1, 1]])

Pictorial Presentation:

NumPy array: ones_like() function

Example: numpy.ones_like where data type is int

>>> import numpy as np
>>> y = np.arange(3, dtype=float)
>>> y
array([ 0.,  1.,  2.])
>>> np.ones_like(y)
array([ 1.,  1.,  1.])
>>> a = np.arange(5, dtype=int)
>>> a
array([0, 1, 2, 3, 4])
>>> np.ones_like(a)
array([1, 1, 1, 1, 1])

Pictorial Presentation:

NumPy array: ones_like() function

Python - NumPy Code Editor:

Previous: ones()
Next: zeros()

Follow us on Facebook and Twitter for latest update.