ในการพิจารณาประเภททั่วไปตามกฎการบีบบังคับมาตรฐาน ให้ใช้เมธอด numpy.find_common_type() ใน Python numpy อาร์กิวเมนต์ที่ 1 คือรายการของ dtypes หรือ dtype convertible object ซึ่งเป็นตัวแทนของอาร์เรย์ อาร์กิวเมนต์ที่ 2 คือรายการของ dtypes หรือ dtype convertible object ที่แสดงสเกลาร์
วิธี find_common_type() จะคืนค่าประเภทข้อมูลทั่วไป ซึ่งเป็นค่าสูงสุดของ ofarray_types โดยไม่สนใจ scalar_types เว้นแต่ว่าค่าสูงสุดของ scalar_types เป็นประเภทอื่น (dtype.kind) หากไม่เข้าใจชนิด จะไม่มีการส่งคืน
ขั้นตอน
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import numpy as np
การใช้เมธอด find_common_type() ใน Numpy กำหนดประเภททั่วไปตามกฎเกณฑ์บังคับ -
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([], [np.int64, np.float32, complex]))
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([np.float32], [complex]))
print("Result...",np.find_common_type([np.float64], [complex]))
print("Result...",np.find_common_type(['f4', 'i4'], ['c8']))
print("Result...",np.find_common_type([np.int64], [complex]))
print("Result...",np.find_common_type([np.int64], [np.float64])) ตัวอย่าง
import numpy as np
# To determine common type following standard coercion rules, use the numpy.find_common_type() method in Python numpy
# The 1st argument is a list of dtypes or dtype convertible objects representing arrays.
# The 2nd argument is A list of dtypes or dtype convertible objects representing scalars.
print("Using the find_common_type() method in Numpy\n")
# Determine common type following standard coercion rules
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([], [np.int64, np.float32, complex]))
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([np.float32], [complex]))
print("Result...",np.find_common_type([np.float64], [complex]))
print("Result...",np.find_common_type(['f4', 'i4'], ['c8']))
print("Result...",np.find_common_type([np.int64], [complex]))
print("Result...",np.find_common_type([np.int64], [np.float64])) ผลลัพธ์
Using the find_common_type() method in Numpy Result... float32 Result... complex128 Result... float32 Result... complex128 Result... complex128 Result... complex128 Result... complex128 Result... float64