def myequal(i,j):
# scalar comparison function of your own design
if isinstance(i,str):
return i==j
else:
return 1e04>abs(i-j)
作为对象数据类型的示例数组:
In [74]: c = np.array([[1.0, "Cat"], [1.00001, 2.00001]],object)
...: d = np.array([[1.000001, "Dog"], [1.00001, 2.00001]],object)
...: e = np.array([[1.000001, "Cat"], [1.00001, 2.00001]],object)
In [75]: c
Out[75]:
array([[1.0, 'Cat'],
[1.00001, 2.00001]], dtype=object)
In [76]: d
Out[76]:
array([[1.000001, 'Dog'],
[1.00001, 2.00001]], dtype=object)
In [77]: e
Out[77]:
array([[1.000001, 'Cat'],
[1.00001, 2.00001]], dtype=object)
使用
frompyfunc
应用
myequal
到数组的元素。基本上它负责广播迭代
In [78]: f = np.frompyfunc(myequal,2,1)
In [79]: f(c,d)
Out[79]:
array([[True, False],
[True, True]], dtype=object)
In [80]: f(c,e)
Out[80]:
array([[True, True],
[True, True]], dtype=object)
没有
object
DTYPE,您的数组是字符串DTYPE,唯一常见的DTYPE:
In [81]: np.array([[1.0, "Cat"], [1.00001, 2.00001]])
Out[81]:
array([['1.0', 'Cat'],
['1.00001', '2.00001']], dtype='<U32')
这会导致
allclose/isclose
因为无法测试字符串
np.inf
:
In [82]: np.isclose(_,_)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-82-c2e4de5fe672> in <module>()
----> 1 np.isclose(_,_)
/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in isclose(a, b, rtol, atol, equal_nan)
2330 y = array(y, dtype=dt, copy=False, subok=True)
2331
-> 2332 xfin = isfinite(x)
2333 yfin = isfinite(y)
2334 if all(xfin) and all(yfin):
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
np.isfinite
适用于数值数组,而不是字符串数组。