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')
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:
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()
- 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