Home » How to Fill NumPy Array with Values (2 Examples)

How to Fill NumPy Array with Values (2 Examples)

by Erma Khan

You can use the following methods to fill a NumPy array with values:

Method 1: Use np.full()

#create NumPy array of length 10 filled with 3's
my_array = np.full(10, 3)

Method 2: Use fill()

#create empty NumPy array with length of 10
my_array = np.empty(10)

#fill NumPy array with 3's
my_array.fill(3)

The following examples show how to use each function in practice.

Example 1: Use np.full()

The following code shows how to use the np.full() function to fill up a NumPy array of length 10 with the value 3 in each position:

import numpy as np

#create NumPy array of length 10 filled with 3's
my_array = np.full(10, 3)

#view NumPy array
print(my_array)

[3 3 3 3 3 3 3 3 3 3]

The NumPy array is filled with a value of 3 in each position.

We can use similar syntax to create a NumPy array of any size.

For example, the following code shows how to create a NumPy array with 7 rows and 2 columns:

import numpy as np

#create NumPy array filled with 3's
my_array = np.full((7, 2), 3)

#view NumPy array
print(my_array)

[[3 3]
 [3 3]
 [3 3]
 [3 3]
 [3 3]
 [3 3]
 [3 3]]

The result is a NumPy array with 7 rows and 2 columns where each position is filled with a value of 3.

Example 2: Use fill()

The following code shows how to use the fill() function to fill up an empty NumPy array with the value 3 in each position:

#create empty NumPy array with length of 10
my_array = np.empty(10)

#fill NumPy array with 3's
my_array.fill(3)

#view NumPy array
print(my_array)

[3. 3. 3. 3. 3. 3. 3. 3. 3. 3.]

The result is a NumPy array in which each position contains the value 3.

Additional Resources

The following tutorials explain how to perform other common tasks in Python:

How to Replace Elements in NumPy Array
How to Count Unique Values in NumPy Array
How to Filter a NumPy Array

Related Posts