2

I have some data that is missing values here and there. I need to replace the NaN with zeros, as I do mathematical operations with those elements in the list named ls. I tried a list comprehension, but did not work:

[0 if i==None else i for i in ls]  

Thanks for help/suggestions!

McGrady
  • 10,869
  • 13
  • 47
  • 69
alc
  • 199
  • 3
  • 15
  • 2
    Does this help? http://stackoverflow.com/questions/944700/how-to-check-for-nan-in-python math.isnan(...) – Stephen C Mar 05 '17 at 03:31
  • 6
    Possible duplicate of [How to check for NaN in python?](http://stackoverflow.com/questions/944700/how-to-check-for-nan-in-python) – miradulo Mar 05 '17 at 03:31

2 Answers2

5

This should work:

import math
[0 if math.isnan(i) else i for i in ls] 
Max Weinzierl
  • 1,231
  • 10
  • 13
  • Thanks, but it's not working either. The NaN values are still there in the list. – alc Mar 05 '17 at 04:08
  • Are you sure they are numerical types and not strings? – Max Weinzierl Mar 05 '17 at 04:10
  • Thank you! - you are right - as I was working late, I forgot to check if they are "System.Double" (IronPython) or strings. I ended up changing the entire list to strings, then convert back to numbers. However IronPython didn't like isnan, but it worked with None as the comprehension: [0 if i==None else i for i in ls] – alc Mar 05 '17 at 14:56
-2

Try the following:

from numpy import isnan

[0 if isnan(i) else i for i in ls]
Alex Luis Arias
  • 1,313
  • 1
  • 14
  • 27