2013-08-21 20 views
2

我有一個腳本編寫了一個從文件列創建列表的腳本。在這個列表中有許多隨機放置的nan條目。我如何刪除這些條目? 繼承人我的代碼:如何從我的Python代碼中刪除nans

#import astropy.io.ascii as asciitable 
import numpy as np 
import pylab as plt 

#x=asciitable.read('protected.txt', guess=False,delimiter='\t',fill_values=[('', '-999')]) 
#x=np.genfromtxt('protected.txt', comments='#', delimiter=' ', skiprows=0, skip_header=0, skip_footer=0, converters=None, missing='', missing_values='', filling_values=-999, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True) 
x=np.load('EC/EC_data') 
# Convert columns to float values 
BMI=map(float,x['bmiEC']) 
print BMI 

繼承人的回溯:

TypeError         Traceback (most recent call last) 

/example_bmiEC.py in <module>() 
     8 # Convert columns to float values 

     9 BMI=map(float,x['bmiEC']) 
---> 10 BMI=BMI[~np.isnan(BMI)] 
    11 print BMI 



TypeError: only integer arrays with one element can be converted to an index 
WARNING: Failure executing file: <example_bmiECFSPR.py> 
+0

你能否清楚解釋一下'nan entry'是什麼? /爲什麼你的一半代碼被註釋掉了?你到底在問什麼?你有什麼嘗試? –

+0

可能的重複的[如何檢查蟒蛇中的NaN?](http://stackoverflow.com/questions/944700/how-to-check-for-nan-in-python) –

+0

是否要刪除NaNs結果列表,還是你想修復它,以便它們不出現在第一位? – JJJ

回答

3
>>> import numpy as np 
>>> a = np.array([1, 2, 3., np.nan, 4, np.nan]) 
>>> a = a[~np.isnan(a)] 
>>> a 
array([ 1., 2., 3., 4.]) 
+0

這樣一段美麗的代碼。 –

+1

與'〜'運算符類似,你可以使用'[np.logical_not(np.isnan(a))]' –

+0

@SaulloCastro這兩種工作對我來說都不是,我得到一個錯誤說'只有一個元素的整數數組可以被轉換爲索引' – blablabla

相關問題