返回一個與給定陣列形狀相同的新陣列,但更改NumPy中的預設型別
要返回一個與給定陣列形狀和型別相同的新陣列,請在Python NumPy中使用**numpy.empty_like()**方法。它返回一個未初始化(任意)資料的陣列,其形狀和型別與原型相同。這裡第一個引數是原型的形狀和資料型別(類似陣列),這些屬性定義了返回陣列的相同屬性。第二個引數是**dtype**,即我們想要的結果陣列的資料型別。
順序會覆蓋結果的記憶體佈局。“C”表示C順序,“F”表示F順序,“A”表示如果原型是Fortran連續的則為“F”,否則為“C”。“K”表示儘可能匹配原型的佈局。形狀會覆蓋結果的形狀。如果order='K'並且維數不變,則將嘗試保持順序,否則,隱含order='C'。overrides引數會覆蓋結果的資料型別。
如果subok引數為True,則新建立的陣列將使用原型的子類型別,否則它將是基類陣列。預設為True。
步驟
首先,匯入所需的庫:
import numpy as np
使用Python NumPy中的numpy.array()方法建立一個新陣列:
arr = np.array([[35.7, 56.2, 66.4], [88.2, 73.7, 98.3]])
顯示陣列:
print("Array...
",arr)獲取陣列的型別:
print("
Array type...
", arr.dtype)
獲取陣列的維度:
print("
Array Dimensions...
", arr.ndim)要返回一個與給定陣列形狀和型別相同的新陣列,請在Python NumPy中使用numpy.empty_like()方法:
newArr = np.empty_like(arr, dtype = int)
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.7, 56.2, 66.4], [88.2, 73.7, 98.3]])
# 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.
# The 2nd parameter is the dtype i.e. the data-type we want for the resultant array
newArr = np.empty_like(arr, dtype = int)
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.7 56.2 66.4] [88.2 73.7 98.3]] Array type... float64 Array Dimensions... 2 New Array.. [[4630221145643784602 4633106264155068826 4634372901550266778] [4635906940173339853 4634886593382763725 4636617664489534259]] New Array type... int64 New Array Dimensions... 2
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP