NumPy: Create an array of equal shape and data type of a given array with fixed value
NumPy: Basic Exercise-55 with Solution
Write a NumPy program to create an array of equal shape and data type for a given array.
Sample Solution:
Python Code:
import numpy as np
nums = np.array([[5.54, 3.38, 7.99],
[3.54, 8.32, 6.99],
[1.54, 2.39, 9.29]])
print("Original array:")
print(nums)
print("\nNew array of equal shape and data type of the said array filled by 0:")
print(np.zeros_like(nums))
Sample Output:
Original array: [[5.54 3.38 7.99] [3.54 8.32 6.99] [1.54 2.39 9.29]] New array of equal shape and data type of the said array filled by 0: [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]
Explanation:
In the above code -
np.array(...) creates a 3x3 NumPy array with the given values and stores in a variable ‘nums’.
print(np.zeros_like(nums)): The np.zeros_like() function takes the input array nums and creates a new NumPy array with the same shape (3x3) and data type (float) as nums. The new array is filled with zeros and the results are printed.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: NumPy program to replace all numbers in a given array which is equal, less and greater to a given number.
Next: NumPy program to create a three-dimension array with shape (3,5,4) and set to a variable.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics