numpy.ndarray.fill() in Python
Last Updated :
28 Dec, 2018
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 fill()
function.
Syntax : ndarray.fill(value)
Parameters:
value : All elements of a will be assigned this value.
Code #1:
import numpy as geek
a = geek.empty([ 3 , 3 ])
for i in range ( 3 ):
for j in range ( 3 ):
a[i][j] = 1
print ( "a is : \n" , a)
a.fill( 1 )
print ( "\nAfter using fill() a is : \n" , a)
|
Output:
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.]]
Code #2:
import numpy as geek
a = geek.arange( 5 )
print ( "a is \n" , a)
a.fill( 0 )
print ( "\nNow a is :\n" , a)
|
Output:
a is
[0 1 2 3 4]
Now a is :
[0 0 0 0 0]
Code #3: numpy.ndarray.fill() also works on multidimensional array.
import numpy as geek
a = geek.empty([ 3 , 3 ])
a.fill( 0 )
print ( "a is :\n" , a)
|
Output:
a is :
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...