16

how can I replace the NaN value in an array, zero if an operation is performed such that as a result instead of the NaN value is zero operations as

0 / 0 = NaN can be replaced by 0

Ricardo Rod
  • 8,453
  • 9
  • 27
  • 39

4 Answers4

31

If you have Python 2.6 you have the math.isnan() function to find NaN values.

With this we can use a list comprehension to replace the NaN values in a list as follows:

import math
mylist = [0 if math.isnan(x) else x for x in mylist]

If you have Python 2.5 we can use the NaN != NaN trick from this question so you do this:

mylist = [0 if x != x else x for x in mylist]
Community
  • 1
  • 1
David Webb
  • 190,537
  • 57
  • 313
  • 299
5
import numpy
a=numpy.array([1,2,3,'NaN',4])
s=numpy.isnan(a)
a[s]=0.0
dimo414
  • 47,227
  • 18
  • 148
  • 244
SoonSYJ
  • 201
  • 1
  • 3
  • 11
3

There is also a pandas solution to this.


import pandas as pd

mylist = [2.3, pd.NA, 1.1, 0.7]
mylist = [0 if pd.isna(x) else x for x in mylist]
0

import numpy

alpha = numpy.array([1,2,3,numpy.nan,4])

n = numpy.nan_to_num(alpha)

print(n)

output : array([1., 2., 3., 0., 4.])

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 19 '22 at 06:49
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Sep 09 '22 at 06:38