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.
Syntax:
numpy.ones_like(a, dtype=None, order='K', subok=True)
Version: 1.15.0
Parameters:
Name | Description | Required / Optional |
---|---|---|
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:
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:
Python - NumPy Code Editor:
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework