numpy.exceptions.DTypePromotionError#

异常 exceptions.DTypePromotionError[源代码]#

无法将多个数据类型(DType)转换为通用数据类型。

当数据类型无法转换为单个通用数据类型时,将引发此异常,该异常派生自 TypeError。这可能是因为它们属于不同类别/类,或者同类中不兼容的实例(参见示例)。

备注

许多函数会使用类型提升来找到正确的结果和实现。对于这些函数,此错误通常会与一个更具体的错误链式出现,表明未找到输入数据类型的实现。

通常,当两个数组的数据类型在根本上不同,导致 arr1 == arr2 可以安全地返回全为 False 时,这两种数据类型之间的提升应被视为“无效”。

示例

日期时间(Datetimes)和复数是互不兼容的类别,无法进行类型提升

>>> 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]'>)

例如,对于结构化数据类型,当两个结构化数据类型的字段数量不匹配时,结构可能会不匹配,并会引发相同的 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.