如何从python cod中删除nans

2024-06-14 22:23:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个脚本,其中一个列表是从一个文件的列中创建的。在这个列表中,随机放置了许多nan条目。如何删除这些条目? 这是我的代码:

#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>

Tags: toimportnonefalsetrue列表asnp
2条回答
>>> 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.])

How to check for NaN in python?

看到这个答案

基本上使用函数math.isnan()

>>> import math
>>> x=float('nan')
>>> math.isnan(x)
True
>>>

相关问题 更多 >