在NumPy中返回一個與給定陣列形狀和型別相同,並更改順序為K樣式的新陣列


要返回一個與給定陣列形狀和型別相同的新陣列,請在Python NumPy中使用**numpy.empty_like()**方法。它返回一個未初始化(任意)資料的陣列,其形狀和型別與原型相同。這裡的第一個引數是原型(類似陣列)的形狀和資料型別,它們定義了返回陣列的這些相同屬性。我們使用“**order**”引數將順序設定為'K'樣式。'K'表示儘可能緊密地匹配原型的佈局。

order引數會覆蓋結果的記憶體佈局。'C'表示C順序,'F'表示Fortran順序,'A'表示如果原型是Fortran連續的則為'F',否則為'C'。'K'表示儘可能緊密地匹配原型的佈局。shape引數會覆蓋結果的形狀。如果order='K'並且維數不變,則會嘗試保持順序,否則,則隱含order='C'。overrides引數會覆蓋結果的資料型別。

如果subok引數為True,則新建立的陣列將使用原型的子類型別,否則它將是基類陣列。預設為True。

步驟

首先,匯入所需的庫:

import numpy as np

使用array()方法建立一個NumPy三維陣列。我們添加了int型別的元素:

arr = np.array([ [[5,10],[15,20]],[[25,30],[35,40]],[[50,60],[70,80]]])

顯示陣列:

print("Array...
",arr)

獲取陣列的型別:

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

獲取陣列的維度:

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

要返回一個與給定陣列形狀和型別相同的新陣列,請在Python NumPy中使用numpy.empty_like()方法。返回一個未初始化(任意)資料的陣列,其形狀和型別與原型相同。我們使用“order”引數將順序設定為'K'樣式:

newArr = np.empty_like(arr, order = 'K')
print("
New Array..
", newArr)

獲取新陣列的型別:

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

獲取新陣列的維度:

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

示例

import numpy as np

# Creating a numpy Three-Dimensional array using the array() method
# We have added elements of int type
arr = np.array([[[5,10],[15,20]],[[25,30],[35,40]],[[50,60],[70,80]]])

# 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 a new array with the same shape and type as a given array, use the numpy.empty_like() method in Python Numpy # It returns the array of uninitialized (arbitrary) data with the same shape and type as prototype. # The 1st parameter here is the shape and data-type of prototype(array-like) that define these same attributes of the returned array. # We have set the order to 'K' style using the "order" parameter. # ‘K’ means match the layout of prototype as closely as possible. newArr = np.empty_like(arr, order = 'K') 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...
[[[ 5 10]
[15 20]]

[[25 30]
[35 40]]

[[50 60]
[70 80]]]

Array type...
int64

Array Dimensions...
3

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

[[140451415756208 140451415756144]
[140451415756272 140451415626672]]

[[140451415626864 140451415626928]
[140451415626992 140451415627568]]]

New Array type...
int64

New Array Dimensions...
3

更新於:2022年2月8日

97 次瀏覽

啟動您的職業生涯

完成課程獲得認證

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