返回一個用零填充的給定形狀的新陣列,並在 NumPy 中設定所需的陣列資料型別。


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

order 引數建議是否以行主序(C 樣式)或列主序(Fortran 樣式)方式在記憶體中儲存多維資料。

掩碼陣列是標準 numpy.ndarray 和掩碼的組合。掩碼要麼是 nomask,表示關聯陣列的任何值均有效,要麼是一個布林陣列,用於確定關聯陣列的每個元素的值是否有效。

步驟

首先,匯入所需的庫:

import numpy as np
import numpy.ma as ma

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

arr = ma.zeros((5,5), dtype = int)

顯示我們的陣列:

print("Array...
",arr)

獲取資料型別:

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

獲取陣列的維度:

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

獲取陣列的形狀:

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

獲取陣列的元素個數:

print("
Elements in the Array...
",arr.size)

示例

# Python ma.MaskedArray - Return a new array of given shape filled with zeros and also set the desired datatype

import numpy as np
import numpy.ma as ma

# To return a new array of given shape and type, filled with zeros, use the ma.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 = ma.zeros((5,5), dtype = int)

# Displaying our 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("
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]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(5, 5)

Elements in the Array...
25

更新於: 2022年2月3日

瀏覽量 109 次

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.