Creating Arrays with Predefined Values in NumPy is particularly handy in scenarios where you need arrays filled with specific data right from the start. I will show you how to generate array filled with value in Numpy using the Numpy full method.
Using np.full
To create an array and initialize it with a specified value, use the full function.
import numpy as np fill_array = np.full(shape=(3, 4), fill_value='my_fav_value') print(fill_array)
This code snippet demonstrates creating a 3×4 array filled with my_fav_value as its content. The shape parameter is a tuple that defines the dimensions of the resulting array, while the fill_value parameter specifies the constant value with which you want to fill the array.
The full function requires two essential arguments without default values:
Customizing Data Type
You can also specify the data type of the array using the dtype argument:
int_array = np.full((2, 2), 7, dtype=np.int32) print(int_array)
This creates a 2×2 integer array filled with the number 7.