Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace the NaN value zero after an operation with arrays

Tags:

python

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

like image 702
ricardo Avatar asked Nov 26 '09 12:11

ricardo


People also ask

How do you replace NaN with 0 in an array?

nan_to_num() function is used when we want to replace nan(Not A Number) with zero and inf with finite numbers in an array. It returns (positive) infinity with a very large number and negative infinity with a very small (or negative) number.

How do you replace NaN in an array?

In NumPy, to replace missing values NaN ( np. nan ) in ndarray with other numbers, use np. nan_to_num() or np. isnan() .

How do I replace all NaN with 0 in R?

To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0.

What is NaN in an array?

In Python, NumPy NAN stands for not a number and is defined as a substitute for declaring value which are numerical values that are missing values in an array as NumPy is used to deal with arrays in Python and this can be initialized using numpy.


1 Answers

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]
like image 159
Dave Webb Avatar answered Sep 22 '22 01:09

Dave Webb