numpy判断数值类型、过滤出数值型数据的方法


Posted in Python onJune 09, 2018

numpy是无法直接判断出由数值与字符混合组成的数组中的数值型数据的,因为由数值类型和字符类型组成的numpy数组已经不是数值类型的数组了,而是dtype='<U11'。

1、math.isnan也不行,它只能判断float("nan"):

>>> import math 
>>> math.isnan(1) 
False 
>>> math.isnan('a') 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
TypeError: a float is required 
>>> math.isnan(float("nan")) 
True 
>>>

2、np.isnan不可用,因为np.isnan只能用于数值型与np.nan组成的numpy数组:

>>> import numpy as np 
>>> test1=np.array([1,2,'aa',3]) 
>>> np.isnan(test1) 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
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 ''sa 
fe'' 
>>> test2=np.array([1,2,np.nan,3]) 
>>> np.isnan(test2) 
array([False, False, True, False], dtype=bool) 
>>>

解决办法:

方法1:将numpy数组转换为python的list,然后通过filter过滤出数值型的值,再转为numpy, 但是,有一个严重的问题,无法保证原来的索引

>>> import numpy as np 
>>> test1=np.array([1,2,'aa',3]) 
>>> list1=list(test1) 
>>> def filter_fun(x): 
... try: 
...  return isinstance(float(x),(float)) 
... except: 
...  return False 
... 
>>> list(filter(filter_fun,list1)) 
['1', '2', '3'] 
>>> np.array(filter(filter_fun,list1)) 
array(<filter object at 0x0339CA30>, dtype=object) 
>>> np.array(list(filter(filter_fun,list1))) 
array(['1', '2', '3'], 
 dtype='<U1') 
>>> np.array([float(x) for x in filter(filter_fun,list1)]) 
array([ 1., 2., 3.]) 
>>>

方法2:利用map制作bool数组,然后再过滤数据和索引:

>>> import numpy as np
>>> test1=np.array([1,2,'aa',3])
>>> list1=list(test1)
>>> def filter_fun(x):
... try:
...  return isinstance(float(x),(float))
... except:
...  return False
...
>>> import pandas as pd
>>> test=pd.DataFrame(test1,index=[1,2,3,4])
>>> test
 0
1 1
2 2
3 aa
4 3
>>> index=test.index
>>> index
Int64Index([1, 2, 3, 4], dtype='int64')
>>> bool_index=map(filter_fun,list1)
>>> bool_index=list(bool_index) #bool_index这样的迭代结果只能list一次,一次再list时会是空,所以保存一下list的结果
>>> bool_index
[True, True, False, True]
>>> new_data=test1[np.array(bool_index)]
>>> new_data
array(['1', '2', '3'],
 dtype='<U11')
>>> new_index=index[np.array(bool_index)]
>>> new_index
Int64Index([1, 2, 4], dtype='int64')
>>> test2=pd.DataFrame(new_data,index=new_index)
>>> test2
 0
1 1
2 2
4 3
>>>

以上这篇numpy判断数值类型、过滤出数值型数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python连接mysql数据库示例(做增删改操作)
Dec 31 Python
Python实现子类调用父类的方法
Nov 10 Python
windows系统下Python环境搭建教程
Mar 28 Python
Python中用psycopg2模块操作PostgreSQL方法
Nov 28 Python
Python 2.7中文显示与处理方法
Jul 16 Python
解决Python中list里的中文输出到html模板里的问题
Dec 17 Python
Pycharm 实现下一个文件引用另外一个文件的方法
Jan 17 Python
Python 串口读写的实现方法
Jun 12 Python
tensorflow之变量初始化(tf.Variable)使用详解
Feb 06 Python
Python文字截图识别OCR工具实例解析
Mar 05 Python
Python高并发和多线程有什么关系
Nov 14 Python
Python实现简单得递归下降Parser
May 02 Python
python中使用iterrows()对dataframe进行遍历的实例
Jun 09 #Python
pandas 小数位数 精度的处理方法
Jun 09 #Python
Numpy数据类型转换astype,dtype的方法
Jun 09 #Python
Python DataFrame设置/更改列表字段/元素类型的方法
Jun 09 #Python
浅谈DataFrame和SparkSql取值误区
Jun 09 #Python
基于DATAFRAME中元素的读取与修改方法
Jun 08 #Python
pandas Dataframe行列读取的实例
Jun 08 #Python
You might like
屏蔽浏览器缓存另类方法
2006/10/09 PHP
php 生成文字png图片的代码
2011/04/17 PHP
php学习之 循环结构实现代码
2011/06/09 PHP
判断PHP数组是否为空的代码
2011/09/08 PHP
ThinkPHP分页类使用详解
2014/03/05 PHP
php实现建立多层级目录的方法
2014/07/19 PHP
PHP调用API接口实现天气查询功能的示例
2017/09/21 PHP
php 判断IP为有效IP地址的方法
2018/01/28 PHP
PHP基于递归算法解决兔子生兔子问题
2018/05/11 PHP
PHP中通过getopt解析GNU C风格命令行选项
2019/11/18 PHP
JavaScript 判断指定字符串是否为有效数字
2010/05/11 Javascript
JavaScript.The.Good.Parts阅读笔记(二)作用域&amp;闭包&amp;减缓全局空间污染
2010/11/16 Javascript
Javascript Ajax异步读取RSS文档具体实现
2013/12/12 Javascript
node.js中的socket.io入门实例
2014/04/26 Javascript
每天一篇javascript学习小结(Array数组)
2015/11/11 Javascript
JS提示:Uncaught SyntaxError:Unexpected token ) 错误的解决方法
2016/08/19 Javascript
WEB 前端开发中防治重复提交的实现方法
2016/10/26 Javascript
vue页面使用阿里oss上传功能的实例(一)
2017/08/09 Javascript
AngularJS 中ui-view传参的实例详解
2017/08/25 Javascript
js实现随机8位验证码
2020/07/24 Javascript
使用Python OpenCV为CNN增加图像样本的实现
2019/06/10 Python
详解Python利用random生成一个列表内的随机数
2019/08/21 Python
opencv-python 读取图像并转换颜色空间实例
2019/12/09 Python
python 如何设置守护进程
2020/10/29 Python
Selenium Webdriver元素定位的八种常用方式(小结)
2021/01/13 Python
pytorch __init__、forward与__call__的用法小结
2021/02/27 Python
python上下文管理的使用场景实例讲解
2021/03/03 Python
关于canvas.toDataURL 在iOS运行失败的问题解决
2020/09/16 HTML / CSS
澳大利亚购买健身器材网站:Gym Direct
2019/12/19 全球购物
保护环境倡议书
2014/04/14 职场文书
县长“四风”对照检查材料思想汇报
2014/10/05 职场文书
后进生评语大全
2015/01/04 职场文书
电影雨中的树观后感
2015/06/15 职场文书
go使用Gin框架利用阿里云实现短信验证码功能
2021/08/04 Golang
Python使用PyYAML库读写yaml文件的方法
2022/04/06 Python
分享Python异步爬取知乎热榜
2022/04/12 Python