运行此行后,我收到以下错误:类型错误:ufunc 'isfinite' 不支持输入类型,并且根据强制转换规则"safe",无法安全地将输入强制转换为任何受支持的类型
df[~( (pd.np.isclose(df.Sizes.round(3), df.Volumes)) & (df['color'] == 'Blue') )]
我该如何解决它?
In [152]: df=pd.DataFrame(np.arange(12.).reshape(4,3), columns=['one','two','three'])
In [153]: df.three[:] = ['a',np.nan,4,3.2]
In [154]: df
Out[154]:
one two three
0 0.0 1.0 a
1 3.0 4.0 nan
2 6.0 7.0 4
3 9.0 10.0 3.2
In [155]: pd.np.isclose(df.one.round(3), df.two)
Out[155]: array([False, False, False, False])
In [156]: pd.np.isclose(df.one.round(3), df.three)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-156-d99a19b1d9b5> in <module>
----> 1 pd.np.isclose(df.one.round(3), df.three)
/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in isclose(a, b, rtol, atol, equal_nan)
2520
2521 xfin = isfinite(x)
-> 2522 yfin = isfinite(y)
2523 if all(xfin) and all(yfin):
2524 return within_tol(x, y, atol, rtol)
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''
对两列float32
的测试有效,但当一列是具有非数值的对象 dtype 时,会引发此错误。
当我比较两个不同函数的结果时,我遇到了这样的问题(在实现中具有不同的写作风格;上述链接中准备好的介质数据集用于评估(,尽管结果数组中的所有数据都属于同一类型np.float64
(它也通过循环每个值来检查assert type(result[i]) == np.float64
;此外,数组也是相同类型的,形状相同(。我只是通过指定数组的类型来解决问题,再次手动使用 .astype(np.float64)
.所以,在我的测试中:
ex = elapses(r, pos, gap, ends_ind, elem_vert, contact_poss)
new = elapses_numba(r, pos, gap, ends_ind, elem_vert, contact_poss)
np.allclose(ex, new) ----> The error
np.allclose(ex.astype(np.float64), new.astype(np.float64)) ----> True
在您的代码中,类似于以下更改的内容可能是解决方案(如果我们检查了所有值都np.float64
但尚未收到错误(:
np.isclose(df.Sizes.round(3).astype(np.float64), df.Volumes.astype(np.float64))