在 NumPy 中返回一個與給定陣列形狀相同但型別不同的零陣列


要返回一個與給定陣列形狀相同但型別不同的零陣列,請在 Python NumPy 中使用 **numpy.zeros_like()** 方法。第一個引數是陣列的形狀和資料型別,這些屬性定義了返回陣列的相同屬性。第二個引數是 **dtype**,即我們希望結果陣列的資料型別。

dtype 會覆蓋結果的資料型別。order 引數會覆蓋結果的記憶體佈局。“C”表示 C 順序,“F”表示 F 順序,“A”表示如果 a 是 Fortran 連續的則為“F”,否則為“C”。“K”表示儘可能地匹配 a 的佈局。如果 subok 引數為 True,則新建立的陣列將使用 a 的子類型別,否則它將是基類陣列。預設為 True。

步驟

首先,匯入所需的庫 -

import numpy as np

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

arr = np.array([[35, 56, 66], [88, 73, 98]])

顯示陣列 -

print("Array...
",arr)

獲取陣列的型別 -

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

獲取陣列的維度 -

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

要返回一個與給定陣列形狀相同但型別不同的零陣列,請在 Python NumPy 中使用 numpy.zeros_like() 方法。第二個引數是 dtype,即我們希望結果陣列的資料型別 -

newArr = np.zeros_like(arr, dtype = float)
print("
New Array..
", newArr)

獲取新陣列的型別 -

print("
New Array type...
", newArr.dtype)

獲取新陣列的維度 -

print("
New Array Dimensions...
", newArr.ndim)

示例

import numpy as np

# Create a new array using the numpy.array() method in Python Numpy
arr = np.array([[35, 56, 66], [88, 73, 98]])

# Display the array
print("Array...
",arr) # Get the type of the array print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
", arr.ndim) # To return an array of zeroes with the same shape as a given array but with a different type, use the numpy.zeros_like() method in Python Numpy # The 1st parameter here is the shape and data-type of array-like that define these same attributes of the returned array. # The 2nd parameter is the dtype i.e. the data-type we want for the resultant array newArr = np.zeros_like(arr, dtype = float) print("
New Array..
", newArr) # Get the type of the new array print("
New Array type...
", newArr.dtype) # Get the dimensions of the new array print("
New Array Dimensions...
", newArr.ndim)

輸出

Array...
[[35 56 66]
[88 73 98]]

Array type...
int64

Array Dimensions...
2

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

New Array type...
float64

New Array Dimensions...
2

更新於: 2022年2月10日

138 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.