NumPy - Array Creation using Ones and Zeros

In this chapter, we will see how to create an array using One's and Zero's

1. numpy.empty

Return a new array of given shape and type, without initializing entries.

Note: It requires the user to manually set all the values in the array, and should be used with caution.

Example 1:

#Code to create empty array
import numpy as np
np.empty([2, 2])

Output:
#uninitialized
[[3.81391429e+180 4.53580024e+217]
 [5.16174075e-109 4.00979049e+087]] 

2. numpy.zeros

Return a new array of given shape and type, filled with zeros.

Example 1:

# Array of three zeros. Default dtype is float 
import numpy as np
a = np.zeros(3) 
print(a)

Output:
[0. 0. 0.]

Example 2:

# Array of zeros in 3*3 shape. Default dtype is float 
import numpy as np
b = np.zeros((3, 3))
print(b)

Output:
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

3. numpy.ones

Return a new array of given shape and type, filled with ones.

Example 1:

#Code to create array with ones as per shape
import numpy as np
a = np.ones(3) 
print(a)

Output:
[1. 1. 1.]

Example 2:

#Code to create array with ones as per 3*3 shape
import numpy as np
b = np.ones((3, 3))
print(b)

Output:
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

4. numpy.eye

Return a 2-D array with ones on the diagonal and zeros elsewhere. It is also called as Diagonal matrix.

Example 1:

import numpy as np
a = np.eye(2) 
print(a)

Output:
[[1. 0.]
 [0. 1.]]

Example 2:

import numpy as np
b = np.eye(3) 
print(b)

Output:
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

5. numpy.full

Return a new array of given shape and type, filled with fill_value.

Example 1:

#Code to create array as per mentioned shape and value
import numpy as np
a = np.full((2, 4), 5)
print(a)

Output:
[[5 5 5 5]
 [5 5 5 5]]

Example 2:

#Code to create array as per mentioned shape and value
import numpy as np
b = np.full((3, 2), 10)
print(b)

Output:
[[10 10]
 [10 10]
 [10 10]]
Total Website Visits: 40440
© Copyright 2018 - 2020. All Rights Reserved.

Developed by Vinoth Rathinam