How to generate array filled with value in Numpy?

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.

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

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 Convert Numpy Array to Boolean Value

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)

    This creates a 2×2 integer array filled with the number 7.

    See also  How to calculate mean in Numpy?