numpy.ndarray.fill() en Python

El método numpy.ndarray.fill() se usa para llenar la array numpy con un valor escalar.

Si tenemos que inicializar una array numpy con un valor idéntico, entonces usamos numpy.ndarray.fill(). Supongamos que tenemos que crear una array NumPy a de longitud n, cada elemento del cual es v. Luego usamos esta función como a.fill(v). No necesitamos usar bucles para inicializar una array si estamos usando esta fill()función.

Sintaxis : ndarray.fill(valor)

Parámetros:
valor : A todos los elementos de a se les asignará este valor.

Código #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)
       
Producción:

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.]]

Código #2:

# 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)
       
Producción:

a is 
 [0 1 2 3 4]

Now a is :
 [0 0 0 0 0]

 
Código #3: numpy.ndarray.fill() también funciona en arreglos multidimensionales.

# 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)
Producción:

a is :
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

Publicación traducida automáticamente

Artículo escrito por ArkadipGhosh y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *