Python Numpy:找到list中的np.nan值方法

yipeiwu_com6年前Python基础

这个问题源于在训练机器学习的一个模型时,使用训练数据时提示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()的文档

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

以上这篇Python Numpy:找到list中的np.nan值方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python2和Python3中print的用法示例总结

前言 最近在学习python,对于python的print一直很恼火,老是不按照预期输出。在python2中print是一种输出语句,和if语句,while语句一样的东西,在python...

Python3.6通过自带的urllib通过get或post方法请求url的实例

废话不多说,直接上代码: # coding:utf-8 from urllib import request from urllib import parse url = "http...

python把数组中的数字每行打印3个并保存在文档中的方法

python把数组中的数字每行打印3个并保存在文档中的方法

如下所示: arrs=[2,15,48,4,5,6,7,6,4,1,2,3,6,6,7,4,6,8] f=open('test.txt','w+') count=0 for temp...

Numpy 改变数组维度的几种方法小结

来自 《Python数据分析基础教程:Numpy 学习指南(第2版)》 Numpy改变数组维度的方法有: reshape() ravel() flatten() 用元组设置维度...

Python3 中把txt数据文件读入到矩阵中的方法

1.实例程序: ''' 数据文件:2.txt内容:(以空格分开每个数据) 1 2 2.5 3 4 4 7 8 7 ''' from numpy import * A = zeros...