在 NumPy 中返回與給定陣列具有相同形狀和型別的新的陣列


要返回一個與給定陣列具有相同形狀和型別的新的陣列,請在 Python NumPy 中使用 **ma.empty_like()** 方法。它返回一個具有與原型相同形狀和型別的未初始化(任意)資料的陣列。

order 引數覆蓋結果的記憶體佈局。“C”表示 C 順序,“F”表示 Fortran 順序,“A”表示如果原型是 Fortran 連續的則為“F”,否則為“C”。“K”表示儘可能接近地匹配原型的佈局。

步驟

首先,匯入所需的庫 -

import numpy as np
import numpy.ma as ma

使用 Python NumPy 中的 numpy.array() 方法建立一個新的陣列 -

arr = np.array([[77, 51, 92], [56, 31, 69], [73, 88, 51], [62, 45, 67]])

顯示我們的陣列 -

print("Array...
",arr)

要返回一個與給定陣列具有相同形狀和型別的新的陣列,請在 Python NumPy 中使用 ma.empty_like() 方法。引數是原型,即原型的形狀和資料型別定義返回陣列的這些相同屬性 -

arr = ma.empty_like(arr)

顯示我們的陣列 -

print("
New Array...
",arr)

獲取陣列的維度 -

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 with the same shape and type as a given array

import numpy as np
import numpy.ma as ma

# Create a new array using the numpy.array() method in Python Numpy
arr = np.array([[77, 51, 92], [56, 31, 69], [73, 88, 51], [62, 45, 67]])

# Displaying our array
print("Array...
",arr) # To return a new array with the same shape and type as a given array, use the ma.empty_like() method in Python Numpy # The parameter is the prototype i.e. the shape and data-type of prototype define these same attributes of the returned array arr = ma.empty_like(arr) # Displaying our array print("
New Array...
",arr) # 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...
[[77 51 92]
[56 31 69]
[73 88 51]
[62 45 67]]

New Array...
[[ 0 0 0]
[ 0 140657801869488 140657802018864]
[140657801869552 140657801869616 140657801869680]
[140657801997616 140657801869744 140657801997680]]

Array Dimensions...
2

Our Array Shape...
(4, 3)

Elements in the Array...
12

更新於: 2022年2月3日

256 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告