เมธอด numpy.can_cast() ส่งคืน True หากสามารถแปลงระหว่างสเกลาร์อาร์เรย์และชนิดข้อมูลได้ตามกฎการหล่อ (casting rule) พารามิเตอร์แรกคือสเกลาร์ ชนิดข้อมูล หรืออาร์เรย์ที่จะแปลงจาก พารามิเตอร์ที่สองคือชนิดข้อมูลที่จะแปลงเป็น
ขั้นตอน
ขั้นแรก ให้นำเข้าไลบรารี:
import numpy as np
ตรวจสอบการแปลงตามกฎการหล่อ:
print("Checking with can_cast() method in Numpy\n")
print("Result...", np.can_cast(np.array(20), 'i1'))
print("Result...", np.can_cast(np.array(280), 'i1'))
print("Result...", np.can_cast(np.array(80), 'u1'))
print("Result...", np.can_cast(np.array(300.7), np.float32))
print("Result...", np.can_cast(np.array(120.6), np.float64))
print("Result...", np.can_cast(np.array(7.2e100), np.float32))
print("Result...", np.can_cast(np.array(6.5e100), np.float64))
ตัวอย่างโค้ดเต็ม
import numpy as np
# numpy.can_cast() ส่งคืน True หากสเกลาร์อาร์เรย์และ dtype แปลงได้ตามกฎการหล่อ
# พารามิเตอร์แรก: สเกลาร์ dtype หรืออาร์เรย์ที่จะแปลงจาก
# พารามิเตอร์ที่สอง: dtype ที่จะแปลงเป็น
print("Checking with can_cast() method in Numpy\n")
print("Result...", np.can_cast(np.array(20), 'i1'))
print("Result...", np.can_cast(np.array(280), 'i1'))
print("Result...", np.can_cast(np.array(80), 'u1'))
print("Result...", np.can_cast(np.array(300.7), np.float32))
print("Result...", np.can_cast(np.array(120.6), np.float64))
print("Result...", np.can_cast(np.array(7.2e100), np.float32))
print("Result...", np.can_cast(np.array(6.5e100), np.float64))
ผลลัพธ์
Checking with can_cast() method in Numpy Result... True Result... False Result... True Result... True Result... True Result... False Result... True