How to generate array filled with value in Numpy?

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.

fill value array numpy

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.

See also  How to Append to an Empty Array in Numpy (with Examples)

fill value array numpy

The full function requires two essential arguments without default values:

  • as a shape you can set a tuple of values as I chose 3 x 4 shaped array
  • fill_value is a value which you want to populate your array
  • 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.

    See also  How to Generate Sequence Arrays in Python with Numpy arange