numpy.exceptions.DTypePromotionError#

exception exceptions.DTypePromotionError[原始碼]#

多個 DType 無法轉換為一個共同的 DType。

此例外衍生自 TypeError,且當 dtype 無法轉換為單一共同 dtype 時引發。這可能是因為它們屬於不同的類別/類別,或是同一個類別的不相容實例(請參閱範例)。

說明

許多函式將使用型別提升來找到正確的結果和實作。對於這些函式,此錯誤通常會與更具體的錯誤鏈結,指出找不到輸入 dtype 的實作。

一般而言,當 arr1 == arr2 可以安全地傳回所有 False 時,型別提升應被視為兩個陣列的 dtype 之間的「無效」,因為 dtype 在本質上是不同的。

範例

日期時間和複數是不相容的類別,無法提升

>>> import numpy as np
>>> np.result_type(np.dtype("M8[s]"), np.complex128)  
Traceback (most recent call last):
 ...
DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not
be promoted by <class 'numpy.dtype[complex128]'>. This means that no common
DType exists for the given inputs. For example they cannot be stored in a
single array unless the dtype is `object`. The full list of DTypes is:
(<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>)

例如,對於結構化 dtype,結構可能不匹配,並且當給定兩個欄位數量不匹配的結構化 dtype 時,也會給出相同的 DTypePromotionError

>>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)])
>>> dtype2 = np.dtype([("field1", np.float64)])
>>> np.promote_types(dtype1, dtype2)  
Traceback (most recent call last):
 ...
DTypePromotionError: field names `('field1', 'field2')` and `('field1',)`
mismatch.