Typeerror: UFUNC ‘isn’t supported for the input types

It took me a lot of time to find the wrong problem, so I hope you can be inspired.

Look at the code explanation

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)

The type dtype of numpy array is 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''

The reason for the error is that the type dtype of numpy is object, not number.

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

Although the previous values are all numbers, the last value is a string, and all values of the array are not of the same type.

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)

Even if the last string is truncated by slicing, the type of the array does not change.

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])

Need to display the array into a numeric type line (here is converted to 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''

When a text value is appended, the type dtype of the array is changed again, which is not numeric. Reuse np.isnan There must be a mistake.

The conclusion is that to avoid errors, the value type in the array must be float or int.

Read More: