Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

python - How can I drop non string type 'nan' from list

I have the data coming from the field. It is in list format. The elements are float. Some unexpected character like nan is seen in the list. But it is not in string format. I tried existing solutions but failed to remove them.

My code:

lst = [1.2,2.3,nan]

newlst = [x for x in lst if str(x) != 'nan']

Present output:

NameError: name 'nan' is not defined

Expected output:

newlst = [1.2,2.3]
question from:https://stackoverflow.com/questions/66052031/how-can-i-drop-non-string-type-nan-from-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a math.isnan() which could be used to identify the NaNs. You can use this inside list comprehension to achieve this as:

>>> import math
>>> lst = [1.2,2.3,float('nan')]

>>> [i  for i in lst if not math.isnan(i)]
[1.2, 2.3]

Additionally, one of the property of 'NaN' numbers is that they return False when compared with itself. You can also utilise this property to identify them and filter them out as:

>>> [i  for i in lst if i==i]
[1.2, 2.3]

Refer Why is NaN not equal to NaN? for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...