国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

numpy判斷數(shù)值類型、過(guò)濾出數(shù)值型數(shù)據(jù)的方法

2020-02-15 21:43:06
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

numpy是無(wú)法直接判斷出由數(shù)值與字符混合組成的數(shù)組中的數(shù)值型數(shù)據(jù)的,因?yàn)橛蓴?shù)值類型和字符類型組成的numpy數(shù)組已經(jīng)不是數(shù)值類型的數(shù)組了,而是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不可用,因?yàn)閚p.isnan只能用于數(shù)值型與np.nan組成的numpy數(shù)組:

>>> 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數(shù)組轉(zhuǎn)換為python的list,然后通過(guò)filter過(guò)濾出數(shù)值型的值,再轉(zhuǎn)為numpy, 但是,有一個(gè)嚴(yán)重的問(wèn)題,無(wú)法保證原來(lái)的索引

>>> 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數(shù)組,然后再過(guò)濾數(shù)據(jù)和索引:

>>> 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 01 12 23 aa4 3>>> index=test.index>>> indexInt64Index([1, 2, 3, 4], dtype='int64')>>> bool_index=map(filter_fun,list1)>>> bool_index=list(bool_index) #bool_index這樣的迭代結(jié)果只能list一次,一次再list時(shí)會(huì)是空,所以保存一下list的結(jié)果>>> bool_index[True, True, False, True]>>> new_data=test1[np.array(bool_index)]>>> new_dataarray(['1', '2', '3'], dtype='<U11')>>> new_index=index[np.array(bool_index)]>>> new_indexInt64Index([1, 2, 4], dtype='int64')>>> test2=pd.DataFrame(new_data,index=new_index)>>> test2 01 12 24 3>>>            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 稷山县| 女性| 师宗县| 开江县| 满洲里市| 宁国市| 越西县| 萨迦县| 方正县| 阿合奇县| 上思县| 济南市| 墨玉县| 股票| 禹州市| 甘孜| 出国| 青河县| 抚松县| 大埔县| 察隅县| 西乡县| 鹤峰县| 渝中区| 德惠市| 扎鲁特旗| 武川县| 汾西县| 青河县| 磐安县| 沙河市| 南岸区| 新宾| 湛江市| 双辽市| 滁州市| 星子县| 巴彦淖尔市| 永和县| 芒康县| 紫阳县|