บทนำ
เมธอด numpy.can_cast() ส่งคืน True หากการแปลงระหว่างชนิดข้อมูล (data types) สามารถเกิดขึ้นได้ตามกฎการแปลง (casting rule) พารามิเตอร์แรกคือชนิดข้อมูลหรืออาร์เรย์ที่จะแปลงจาก พารามิเตอร์ที่สองคือชนิดข้อมูลที่จะแปลงไป
ขั้นตอน
ขั้นแรก ให้นำเข้าไลบรารีที่จำเป็น:
import numpy as np
ใช้ can_cast() ตรวจสอบว่าการแปลงระหว่างชนิดข้อมูลสามารถเกิดขึ้นได้ตามกฎการแปลง:
print("ตรวจสอบด้วยเมธอด can_cast() ใน NumPy\n")
print("ผลลัพธ์...", np.can_cast(np.int32, np.int64))
print("ผลลัพธ์...", np.can_cast(np.float64, complex))
print("ผลลัพธ์...", np.can_cast(complex, float))
print("ผลลัพธ์...", np.can_cast('i8', 'f8'))
print("ผลลัพธ์...", np.can_cast('i8', 'f4'))
print("ผลลัพธ์...", np.can_cast('i4', 'S4'))
ตัวอย่างโค้ดสมบูรณ์
import numpy as np
# numpy.can_cast() ส่งคืน True หากการแปลงระหว่างชนิดข้อมูลสามารถเกิดขึ้นได้ตามกฎการแปลง
# พารามิเตอร์แรกคือชนิดข้อมูลหรืออาร์เรย์ที่จะแปลงจาก
# พารามิเตอร์ที่สองคือชนิดข้อมูลที่จะแปลงไป
print("ตรวจสอบด้วยเมธอด can_cast() ใน NumPy\n")
print("ผลลัพธ์...", np.can_cast(np.int32, np.int64))
print("ผลลัพธ์...", np.can_cast(np.float64, complex))
print("ผลลัพธ์...", np.can_cast(complex, float))
print("ผลลัพธ์...", np.can_cast('i8', 'f8'))
print("ผลลัพธ์...", np.can_cast('i8', 'f4'))
print("ผลลัพธ์...", np.can_cast('i4', 'S4'))
ผลลัพธ์
ตรวจสอบด้วยเมธอด can_cast() ใน NumPy ผลลัพธ์... True ผลลัพธ์... True ผลลัพธ์... False ผลลัพธ์... True ผลลัพธ์... False ผลลัพธ์... False