NumPy - ones() function
The NumPy ones() function returns a new array of specified shape and data type, filled with ones.
Syntax
numpy.ones(shape, dtype=float, order='C')
Parameters
shape |
Required. Specify shape of the returned array in form of int or tuple of ints. |
dtype |
Optional. Specify the desired data-type for the array. Default: float |
order |
Optional. Specify whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory. Two possible values are: C (C-style) and F (Fortran-style). Default: 'C' |
Return Value
Returns an array (ndarray) of ones with the given shape, dtype, and order.
Example: Create 2-D array of ones
In the example below, ones() function is used to create a 2 dimensional array of ones of specified shape.
import numpy as np Arr = np.ones((2,3)) print(Arr)
The output of the above code will be:
[[ 1. 1. 1.] [ 1. 1. 1.]]
Example: ones() function with dtype parameter
The ones() function can be used with dtype parameter to provide the data type of the elements of the array. In the example below, data type of the returned array is complex.
import numpy as np Arr = np.ones((2,2), dtype=complex) print(Arr)
The output of the above code will be:
[[ 1.+0.j 1.+0.j] [ 1.+0.j 1.+0.j]]
❮ NumPy - Functions