numpy.exceptions.DTypePromotionError#

exception exceptions.DTypePromotionError[源代码]#

无法将多个 DTypes 转换为通用类型.

这个异常继承自 TypeError ,当 dtypes 无法转换为单一的公共类型时会引发此异常.这可能是因为它们属于不同的类别/类,或者是不兼容的相同类型的实例(见示例).

备注

许多函数将使用推广来找到正确的结果和实现.对于这些函数,错误通常会与一个更具体的错误链接,指示没有找到适用于输入数据类型的实现.

通常,当两个数组的 arr1 == arr2 可以安全地返回所有 False 因为数据类型根本不同时,在两个数组的数据类型之间的典型推广应被视为”无效”.

示例

日期时间和复数是不可兼容的类,不能被提升:

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

例如,对于结构化的dtypes,结构可能不匹配,当给出两个字段数量不匹配的结构化dtypes时,会给出相同的 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.