numpy.ndarray.fill() in Python
Last Updated :
28 Dec, 2018
Improve
numpy.ndarray.fill() method is used to fill the numpy array with a scalar value.
If we have to initialize a numpy array with an identical value then we use numpy.ndarray.fill(). Suppose we have to create a NumPy array a of length n, each element of which is v. Then we use this function as a.fill(v). We need not use loops to initialize an array if we are using this
Python3 1==
Python3
Python3
fill()
function.
Syntax : ndarray.fill(value) Parameters: value : All elements of a will be assigned this value.Code #1:
# Python program explaining
# numpy.ndarray.fill() function
import numpy as geek
a = geek.empty([3, 3])
# Initializing each element of the array
# with 1 by using nested loops
for i in range(3):
for j in range(3):
a[i][j] = 1
print("a is : \n", a)
# now we are initializing each element
# of the array with 1 using fill() function.
a.fill(1)
print("\nAfter using fill() a is : \n", a)
Output:
Code #2:
a is : [[ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.]] After using fill() a is : [[ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.]]
# Python program explaining
# numpy.ndarray.fill() function
import numpy as geek
a = geek.arange(5)
print("a is \n", a)
# Using fill() method
a.fill(0)
print("\nNow a is :\n", a)
Output:
Code #3: numpy.ndarray.fill() also works on multidimensional array.
a is [0 1 2 3 4] Now a is : [0 0 0 0 0]
# Python program explaining
# numpy.ndarray.fill() function
import numpy as geek
a = geek.empty([3, 3])
# Using fill() method
a.fill(0)
print("a is :\n", a)
Output:
a is : [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]]