當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python numpy.ndarray.fill()用法及代碼示例

numpy.ndarray.fill()方法用於用標量值填充numpy數組。

如果必須使用相同的值初始化numpy數組,則可以使用numpy.ndarray.fill()。假設我們必須創建一個長度為n的NumPy數組a,其每個元素為v。然後我們將此函數用作a.fill(v)。如果我們使用循環,則無需使用循環來初始化數組fill()函數。

用法 : ndarray.fill(value)

參數:
value :將為a的所有元素分配該值。

代碼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) 
       
輸出:
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.]]

代碼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) 
       
輸出:
a is 
 [0 1 2 3 4]

Now a is :
 [0 0 0 0 0]


代碼3:numpy.ndarray.fill()也可用於多維數組。

# 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)
輸出:
a is :
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]


相關用法


注:本文由純淨天空篩選整理自ArkadipGhosh大神的英文原創作品 numpy.ndarray.fill() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。