numpy.can_cast() วิธีการคืนค่า True หากการส่งข้อมูลระหว่างประเภทข้อมูลสามารถเกิดขึ้นได้ตามกฎการแคสต์ พารามิเตอร์ที่ 1 คือชนิดข้อมูลหรืออาร์เรย์ที่จะส่ง พารามิเตอร์ที่ 2 คือประเภทข้อมูลที่จะส่งไป พารามิเตอร์ที่ 3 ควบคุมประเภทการส่งข้อมูลที่อาจเกิดขึ้น โดยมีค่า "ไม่", "เทียบเท่า", "ปลอดภัย", "ชนิดเดียวกัน" และ "ไม่ปลอดภัย"
-
'ไม่' หมายความว่าไม่ควรส่งประเภทข้อมูลเลย
-
'equiv' หมายถึงอนุญาตเฉพาะการเปลี่ยนแปลงลำดับไบต์เท่านั้น
-
"ปลอดภัย" หมายถึงอนุญาตเฉพาะการร่ายที่สามารถรักษาค่าได้
-
'same_kind' หมายถึงอนุญาตเฉพาะการร่ายหรือการร่ายในประเภท เช่น float64 ถึง float32 เท่านั้น
-
"ไม่ปลอดภัย" หมายความว่าสามารถแปลงข้อมูลได้
ขั้นตอน
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import numpy as np
numpy.can_cast() วิธีการคืนค่า True ถ้า cast ระหว่างประเภทข้อมูลสามารถเกิดขึ้นได้ตามกฎ thecasting -
print("Checking with can_cast() method in Numpy\n")
ประเภท "ไม่" −
print("Result...",np.can_cast('i8', 'i8', 'no'))
print("Result...",np.can_cast('<i8', '>i8', 'no')) ประเภท "เทียบเท่า" −
print("Result...",np.can_cast('<i8', '>i8', 'equiv'))
print("Result...",np.can_cast('<i4', '>i8', 'equiv')) ประเภท "ปลอดภัย" −
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