w3resource

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.

This problem involves writing a NumPy program to create a new array with the same shape and data type as a given array. The task requires utilizing NumPy's array creation functionalities, such as "numpy.zeros_like" or "numpy.empty_like", to efficiently generate the new array with the desired properties. By specifying the shape and data type of the original array as parameters, the program ensures the creation of a new array that matches the shape and data type of the given array, facilitating data manipulation and processing tasks.

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))

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/basic/numpy-basic-exercise-55.php