⊕
⊖
Contents
NumPy – Create array with ones
To create a numpy array of specific shape with all the elements initialised to one in Python, we can use numpy.ones() function.
Call numpy.ones() function, and pass the shape (a tuple with lengths of dimensions) as argument to the the function.
Examples
1. Create array with ones of shape (3, 5)
In the following program, we create a numpy array (a 2 dimensional) with all elements in the array set to one, and a shape of (3, 5).
Output
[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]
2. Create array with ones of shape (2, 3, 5)
In the following program, we create a numpy array , a 3-dimensional, with all elements in the array set to one, and a shape of (2, 3, 5).
Output
[[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]
[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]]
Summary
In this NumPy Tutorial, we learned how to create a numpy array with ones in Python using numpy.ones() function.