Today we are going to learn, Methods to create NumPy array using ones() and zeros() functions? of NumPy library.
So let us start with our examples to understand this with hands on practice.
These are Methods to create NumPy array using ones() and zeros() functions?
1. using Zeros() function to create array
NumPy has zeros() function to create arrays with all elements as 0
The syntax is
np.zeros(x,y)
Parameters in syntax:
x = number of rows
y = number of columns in the array
# Example
import numpy as np
array_three = np.zeros((4,4))
print("array three using zero",array_three)
When we will execute this program we will get an array of 4 x 4 size. let us check the Output:
array three using zero
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
2. using ones() function to create array
NumPy has ones() function to create arrays with all elements as 1.
The syntax is :
np.ones(x,y)
Parameters
x = number of rows
y = number of columns in array
# Example
import numpy as np
array_four = np.ones((4,4))
print("array four using ones",array_four)
When we will execute this program we will get an array of 4 x 4 size with all values as 1 . let us check the Output:
array four using ones
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
ones() function can be passed additional arguments as dtype to specify the data type.
import numpy as np
array_five = np.ones((4,4),dtype=np.int16)
print("array five using ones with dtype",array_five)
This will give you output as:
array five using ones with dtype
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]