9.1 C
London
Friday, December 20, 2024
HomePandas in PythonGeneral Functions in PythonHow to Fill NumPy Array with Values (2 Examples)

How to Fill NumPy Array with Values (2 Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories