Today we are going to learn how we can create 2-D NumPy array using Ones_like(),empty_like() and Zeros_like() functions of NumPy Library.
# using ones_like() to create array
NumPy library has a function ones_like() which takes another array and creates an array of the same size with all elements as 1.
Example 1
import numpy as np
array_three = [[0 1]
[2 3]
[4 5]
[6 7]]
array_four = np.ones_like(array_three)
print("2D Array using ones_like",array_four)
Output
2D Array using ones_like [[1 1]
[1 1]
[1 1]
[1 1]]
# using zeros_like() and empty_like() functions
NumPy also have zeros_like() function which takes an array and creates the same size array with elements as 0.
Another function empty_like() works the same way and creates an array with placeholders.
Examples :
import numpy as np
array_three = [[0 1]
[2 3]
[4 5]
[6 7]]
array_five = np.zeros_like(array_three)
print("2D Array using zeros_like",array_five)
Outputs:
2D Array using zeros_like
[[0 0]
[0 0]
[0 0]
[0 0]]
Empty_like()
import numpy as np
array_three = [[0 1]
[2 3]
[4 5]
[6 7]]
array_six = np.empty_like(array_three)
print("2D Array using empty_like",array_six)
Outputs:
2D Array using empty_like
[[ 7864421 7471220]
[ 7536737 7340078]
[ 121 6553721]
[808648704 859255908]]