Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert nan value to zero

Tags:

python

nan

numpy

I have a 2D numpy array. Some of the values in this array are NaN. I want to perform certain operations using this array. For example consider the array:

[[   0.   43.   67.    0.   38.]  [ 100.   86.   96.  100.   94.]  [  76.   79.   83.   89.   56.]  [  88.   NaN   67.   89.   81.]  [  94.   79.   67.   89.   69.]  [  88.   79.   58.   72.   63.]  [  76.   79.   71.   67.   56.]  [  71.   71.   NaN   56.  100.]] 

I am trying to take each row, one at a time, sort it in reversed order to get max 3 values from the row and take their average. The code I tried is:

# nparr is a 2D numpy array for entry in nparr:     sortedentry = sorted(entry, reverse=True)     highest_3_values = sortedentry[:3]     avg_highest_3 = float(sum(highest_3_values)) / 3 

This does not work for rows containing NaN. My question is, is there a quick way to convert all NaN values to zero in the 2D numpy array so that I have no problems with sorting and other things I am trying to do.

like image 284
Curious2learn Avatar asked Feb 26 '11 01:02

Curious2learn


People also ask

Which function will fill 0 in place of NaN?

Pandas replace nan with 0 inplace In this method, the inplace parameter is set to inplace =True which means that it will fill in the null values and directly modify the original Pandas DataFrame. If you set inplace =True then it fills values at an empty place.

How do I replace NaN by zero in R?

Replace NA with 0 in R Data Frame 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.


1 Answers

Where A is your 2D array:

import numpy as np A[np.isnan(A)] = 0 

The function isnan produces a bool array indicating where the NaN values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.

like image 82
Paul Avatar answered Nov 09 '22 23:11

Paul