如何检查给定值是否可以存储在numpy
数组中?
例如:
import numpy as np
np.array(["a","b"])
==> array(['a', 'b'], dtype='|S1')
np.array(["a","b"]) == 1
> __main__:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
==> False
np.array(["a","b"]) == "a"
==> array([ True, False], dtype=bool)
我想要一个np_isinstance
可以做到这一点的函数:
np_isinstance("a", np.array(["a","b"]).dtype)
==> True
np_isinstance(1, np.array(["a","b"]).dtype)
==> False
np_isinstance("a", np.array([1,2,3]).dtype)
==> False
np_isinstance(1, np.array([1,2,3]).dtype)
==> True
到目前为止,我设法想出了
def np_isinstance(o,dt):
return np.issubdtype(np.array([o]).dtype, dt)
但这似乎是错误的,因为它array
在每次调用时分配一个。
人们可能希望numpy.can_cast(from, totype)能完成这项工作,但是,唉,
np.can_cast("a",np.dtype("O"))
> TypeError: did not understand one of the types; 'None' not accepted