返回一個用零填充的指定形狀的新陣列,並在NumPy中設定所需的輸出


要在Python NumPy中返回一個具有給定形狀和型別的用零填充的新陣列,請使用**np.zeros()**方法。第一個引數設定陣列的形狀。第二個引數是陣列所需的資料型別。

dtype是陣列所需的資料型別,例如numpy.int8。預設為numpy.float64。order引數建議是否以行優先(C風格)或列優先(Fortran風格)的順序在記憶體中儲存多維資料。like引數是參考物件,允許建立非NumPy陣列的陣列。如果作為like傳入的類陣列支援__array_function__協議,則結果將由其定義。在這種情況下,它確保建立一個與透過此引數傳入的類陣列相容的陣列物件。

步驟

首先,匯入所需的庫:

import numpy as np

要在Python NumPy中返回一個具有給定形狀和型別的用零填充的新陣列,請使用np.zeros()方法。第二個引數是陣列所需的資料型別:

arr = np.zeros((6,6), dtype = int)

顯示陣列:

print("Array...
",arr)

獲取資料型別:

print("
Array datatype...
",arr.dtype)

獲取陣列的維度:

print("
Array Dimensions...
",arr.ndim)

獲取陣列的形狀:

print("
Our Array Shape...
",arr.shape)

獲取陣列的元素個數:

print("
Number of elements in the Array...
",arr.size)

示例

import numpy as np
import numpy.ma as ma

# To return a new array of given shape and type, filled with zeros, use the np.zeros() method in Python Numpy
# The 1st parameter sets the shape of the array
# The 2nd parameter is the desired data-type for the array
arr = np.zeros((6,6), dtype = int)

# Displaying the array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Number of elements in the Array...
",arr.size)

輸出

Array...
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(6, 6)

Number of elements in the Array...
36

更新於:2022年2月10日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.