TypeError: ufunc ‘isnan‘ not supported for the input types,.....的错误原因

自己碰到的问题,花了不少时间才找到错,所以希望大家有启发。

看代码解释

da1
Out[1]: 
          a   b  c        aa
0  0.200000  a1  1  0.200000
1  0.500000  a2  2  0.500000
2  0.428571  a3  3  0.428571
3       NaN  a2  4       NaN
4  0.833333  a1  5  0.833333
5  0.750000  a1  6  0.750000
6  0.777778  a3  7  0.777778
7       NaN  a1  8       NaN
8      test  a3  9       NaN

In [2]: ddn1 = da1['a'].values

In [3]: ddn1
Out[3]: 
array([0.2, 0.5, 0.42857142857142855, nan, 0.8333333333333334, 0.75,
       0.7777777777777778, nan, 'test'], dtype=object)

numpy数组的类型dtype是object

In [4]: np.isnan(ddn1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-414-406cd3e92434> in <module>
----> 1 np.isnan(ddn1)

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

出现报错的原因是,numpy的类型dtype是object,而不是数字类型。

In [5]: type(ddn1[:8])
Out[5]: numpy.ndarray
In [6]: type(ddn1[8])
Out[6]: str

虽然前面的值都是数字,但最后一个值是字符串,数组全部值不是同一个类型。

In [7]: ddn1 = ddn1[:8]

In [8]: ddn1
Out[8]: 
array([0.2, 0.5, 0.42857142857142855, nan, 0.8333333333333334, 0.75,
       0.7777777777777778, nan], dtype=object)

即使通过切片,把最后的字符串截去,数组的类型也未改变。

ddn1 = ddn1.astype('float')

ddn1
Out[9]: 
array([0.2       , 0.5       , 0.42857143,        nan, 0.83333333,
       0.75      , 0.77777778,        nan])

np.isnan(ddn1)
Out[10]: array([False, False, False,  True, False, False, False,  True])

需要显示的把数组转为数值类型才行(这里是转为float)。

In [11]: ddn1 = np.append(ddn1,'test')

In [12]: ddn1
Out[12]: 
array(['0.2', '0.5', '0.42857142857142855', 'nan', '0.8333333333333334',
       '0.75', '0.7777777777777778', 'nan', 'test'], dtype='<U32')
In [13]: np.isnan(np.append(ddn1,'test'))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-440-26598f53c9e6> in <module>
----> 1 np.isnan(np.append(ddn1,'test'))

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

追加一个文本值,数组的类型dtype又发生了变化,不是数值类型的。再用np.isnan一定会报错。

结论是,如果要避免错误,数组里的值类型必须是float或int。
  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值