w3resource

NumPy: Create an array of equal shape and data type of a given array with fixed value


Create Array of Same Shape & Type

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: