Creating arrays with predefined values in NumPy is useful when you need arrays initialized with specific data from the start. We’ll show how to use the np.full function to generate arrays filled with a value of your choice.
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. The dtype argument ensures that the array is of type int32.