numpy判断数值类型、过滤出数值型数据的⽅法
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
filter过滤对象数组...
>>> 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
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
1 1
2 2
4 3
>>>
以上这篇numpy判断数值类型、过滤出数值型数据的⽅法就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论