Python Numpy:如何找到list中的np.nan值

这个问题源于在训练机器学习的一个模型时,使用训练数据时提示prepare的数据中存在np.nan

报错信息如下:
ValueError: np.nan is an invalid document, expected byte or unicode string.
刚开始不知道为什么会有这个,后来发现是list中存在nan值

下面是找到nan值的方法:
简单找到:

import numpy as np

x = np.array([2,3,np.nan,5,
              np.nan,5,2,3])

for item in x:
    if np.isnan(item):
        print('yes')

拿到index数组:

x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
print(np.argwhere(np.isnan(x)))

output:
array([[1, 2],
[2, 0]])

然而实际上,有些时候,如果是用pandas读出的数据,在list中print时提示为nan,但用isnan方法却并不能正确判断,会提示TypeError,此时需要用pandas.isnull()判断该值是否为空


下面是numpy.isnan()的文档

这里写图片描述

猜你喜欢

转载自blog.csdn.net/ninnyyan/article/details/80564699