一、astype函數(shù) Python

astype函數(shù)是NumPy中的一個重要函數(shù),常用于數(shù)組的數(shù)據(jù)類型轉(zhuǎn)換。它的基本語法是:astype(dtype, order='K', casting='unsafe', subok=True, copy=True),其中dtype參數(shù)表示指定的目標數(shù)據(jù)類型,可以是Python數(shù)據(jù)類型或NumPy中定義的數(shù)據(jù)類型,其余參數(shù)都是可選的。
例如,假設(shè)我們有一個二維數(shù)組x:
import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]]) print(x.dtype) # 輸出:int64
默認情況下,x的數(shù)據(jù)類型為int64。如果我們想將它轉(zhuǎn)換為float類型,可以這樣做:
y = x.astype(float)
print(y.dtype) # 輸出:float64
print(y) # 輸出:[[1. 2.]
# [3. 4.]
# [5. 6.]]
在這個例子中,astype函數(shù)將x數(shù)組的數(shù)據(jù)類型從int64轉(zhuǎn)換為float64。
二、astype不是定義函數(shù)
注意,astype不是Python內(nèi)置函數(shù),它是NumPy庫中定義的一個函數(shù)。如果在使用astype函數(shù)時遇到“astype is not defined”錯誤,可能是因為沒有正確導入NumPy庫或者代碼中的語法錯誤。
例如,以下示例中的代碼會導致“名字 'astype' 未定義”錯誤:
# 錯誤示例 x = [1, 2, 3, 4, 5] y = x.astype(float)
正確的代碼應(yīng)該是:
# 正確示例 import numpy as np x = np.array([1, 2, 3, 4, 5]) y = x.astype(float)
三、參數(shù)說明
1. dtype參數(shù)
dtype參數(shù)是必須指定的,表示目標數(shù)據(jù)類型??梢允荘ython數(shù)據(jù)類型,例如int、float、str等,也可以是NumPy中的數(shù)據(jù)類型,例如np.int32、np.float64等。
如果指定的目標數(shù)據(jù)類型和數(shù)組的原始數(shù)據(jù)類型不一致,astype函數(shù)將會執(zhí)行數(shù)據(jù)類型轉(zhuǎn)換。例如,將整型數(shù)組轉(zhuǎn)換為浮點型數(shù)組:
import numpy as np x = np.array([1, 2, 3]) y = x.astype(float) print(y) # 輸出:[1. 2. 3.]
需要注意的是,如果指定的數(shù)據(jù)類型無法表示原始數(shù)據(jù),astype函數(shù)會執(zhí)行截斷操作,也就是將數(shù)據(jù)截斷至目標數(shù)據(jù)類型的范圍內(nèi)。例如,將大于255的無符號整型數(shù)據(jù)轉(zhuǎn)換為uint8類型:
import numpy as np x = np.array([255, 256, 257], dtype=np.uint16) y = x.astype(np.uint8) print(y) # 輸出:[255 0 1]
2. order參數(shù)
order參數(shù)用于指定數(shù)組的內(nèi)存布局,默認值為'K',表示優(yōu)先使用數(shù)組本身的內(nèi)存布局。當order取值為'C'或'F'時,將強制使用按行排列('C')或按列排列('F')的內(nèi)存布局。
例如,以下示例中的代碼將數(shù)組x從按行排列('C')的內(nèi)存布局轉(zhuǎn)換為按列排列('F')的內(nèi)存布局:
import numpy as np
x = np.array([[1, 2], [3, 4], [5, 6]])
y = x.astype(float, order='F')
print(y.flags) # 輸出:C_CONTIGUOUS : False
# F_CONTIGUOUS : True
# OWNDATA : True
# ...
3. casting參數(shù)
casting參數(shù)用于指定數(shù)據(jù)類型轉(zhuǎn)換時的轉(zhuǎn)換規(guī)則,有三種取值:
'no':不允許任何轉(zhuǎn)換。
'equiv':只允許等價類型轉(zhuǎn)換,例如int轉(zhuǎn)換為float。
'unsafe':允許任何類型轉(zhuǎn)換,即使可能導致數(shù)據(jù)丟失。
例如,以下示例中的代碼不允許將浮點型數(shù)據(jù)轉(zhuǎn)換為整型:
import numpy as np x = np.array([1.2, 2.5, 3.7]) y = x.astype(int, casting='no') # 報錯:Can't cast float64 to int64 without losing precision
4. subok參數(shù)
subok參數(shù)用于指定是否返回一個派生類,默認為True,即返回一個與輸入?yún)?shù)類型相同的派生類。如果取值為False,則返回一個NumPy數(shù)組對象。
以下示例中的代碼將返回一個類型為ndarray_subclass的派生類:
import numpy as np
class ndarray_subclass(np.ndarray):
pass
x = np.array([1, 2, 3], dtype=np.int32).view(ndarray_subclass)
y = x.astype(float, subok=True)
print(type(y)) # 輸出:
5. copy參數(shù)
copy參數(shù)用于指定是否為返回的數(shù)組對象分配新的內(nèi)存,默認為True,即始終創(chuàng)建一個新數(shù)組并復(fù)制數(shù)據(jù)。如果取值為False,則可能直接返回原始數(shù)組的視圖。
例如,以下示例中的代碼直接返回原始數(shù)組的視圖:
import numpy as np x = np.array([1, 2, 3], dtype=np.int32) y = x.astype(float, copy=False) print(y is x) # 輸出:True print(y.base is x) # 輸出:True

京公網(wǎng)安備 11010802030320號