如果根據轉換規則可以發生資料型別之間的轉換,則返回 True,控制 Python 中可能發生的哪種資料轉換。


numpy.can_cast() 方法根據轉換規則返回 True,如果可以發生資料型別之間的轉換。第一個引數是要轉換的資料型別或陣列。第二個引數是要轉換到的資料型別。第三個引數控制可能發生的哪種資料轉換,其值包括 'no'、'equiv'、'safe'、'same_kind' 和 'unsafe'。

  • “no”表示資料型別根本不應該轉換。

  • “equiv”表示僅允許位元組順序更改。

  • “safe”表示僅允許保留值的轉換。

  • “same_kind”表示僅允許安全的轉換或同類轉換,例如 float64 到 float32。

  • “unsafe”表示可以進行任何資料轉換。

步驟

首先,匯入所需的庫 -

import numpy as np

numpy.can_cast() 方法根據轉換規則返回 True,如果可以發生資料型別之間的轉換 -

print("Checking with can_cast() method in Numpy\n")

型別“no” -

print("Result...",np.can_cast('i8', 'i8', 'no'))
print("Result...",np.can_cast('<i8', '>i8', 'no'))

型別“equiv” -

print("Result...",np.can_cast('<i8', '>i8', 'equiv'))
print("Result...",np.can_cast('<i4', '>i8', 'equiv'))

型別“safe” -

print("Result...",np.can_cast('i4', 'i8', 'safe'))
print("Result...",np.can_cast('i8', 'i4', 'safe'))

型別“same_kind” -

print("Result...",np.can_cast('i8', 'i4', 'same_kind'))
print("Result...",np.can_cast('i8', 'i4', 'same_kind'))

示例

import numpy as np

# The numpy.can_cast() method returns True if cast between data types can occur according to the casting rule.

print("Checking with can_cast() method in Numpy\n")

# The type "no"
print("Result...",np.can_cast('i8', 'i8', 'no'))
print("Result...",np.can_cast('<i8', '>i8', 'no'))

# The type "equiv"
print("Result...",np.can_cast('<i8', '>i8', 'equiv'))
print("Result...",np.can_cast('<i4', '>i8', 'equiv'))

# The type "safe"
print("Result...",np.can_cast('i4', 'i8', 'safe'))
print("Result...",np.can_cast('i8', 'i4', 'safe'))

# The type "same_kind"
print("Result...",np.can_cast('i8', 'i4', 'same_kind'))
print("Result...",np.can_cast('i8', 'i4', 'same_kind'))

輸出

Checking with can_cast() method in Numpy

Result... True
Result... False
Result... True
Result... False
Result... True
Result... False
Result... True
Result... True

更新於: 2022年2月25日

109 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告