问题描述
是否可以在numpy中禁用静默转换?
Is there a way to disable silent conversions in numpy?
import numpy as np
a = np.empty(10, int)
a[2] = 4 # OK
a[3] = 4.9 # Will silently convert to 4, but I would prefer a TypeError
a[4] = 4j # TypeError: can't convert complex to long
在分配非ndarray类型的isinstance()
的任何值时,可以将numpy.ndarray
对象配置为返回TypeError
吗?如果不是,最好的替代方法是子类(并覆盖__setattr__
或__setitem__
)吗?
Can numpy.ndarray
objects be configured to return a TypeError
when assigning any value which is not isinstance()
of the ndarray type?If not, would the best alternative be to subclass numpy.ndarray
(and override __setattr__
or __setitem__
)?
推荐答案
不幸的是,numpy
在数组创建中未提供此功能,您可以设置是否仅在转换数组时才允许强制转换(请参阅文档以获取相关信息). numpy.ndarray.astype
).
Unfortunately numpy
doesn't offer this feature in array creation, you can set if casting is allowed only when you are converting an array (check the documentation for numpy.ndarray.astype
).
您可以使用该功能或子类,但也可以考虑使用 模块来创建类型数组:
You could use that feature, or subclass numpy.ndarray
, but also consider using the array
module offered by python itself to create a typed array:
from array import array
a = array('i', [0] * 10)
a[2] = 4 # OK
a[3] = 4.9 # TypeError: integer argument expected, got float
这篇关于禁用numpy中的静默转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!