Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace NaN value with zero in a huge data frame?

Tags:

replace

r

I tried to replace NaN values with zeros using the following script:

rapply( data123, f=function(x) ifelse(is.nan(x),0,x), how="replace" ) # [31]   0.00000000  -0.67994832   0.50287454   0.63979527   1.48410571  -2.90402836 

The NaN value was showing to be zero but when I typed in the name of the data frame and tried to review it, the value was still remaining NaN.

data123$contri_us # [31]          NaN  -0.67994832   0.50287454   0.63979527   1.48410571  -2.90402836 

I am not sure whether the rapply command was actually applying the adjustment in the data frame, or just replaced the value as per shown.

Any idea how to actually change the NaN value to zero?

like image 691
cactussss Avatar asked Aug 09 '13 07:08

cactussss


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 you fill NP NaN with 0?

You can use numpy. nan_to_num : numpy. nan_to_num(x) : Replace nan with zero and inf with finite numbers.


1 Answers

It would seem that is.nan doesn't actually have a method for data frames, unlike is.na. So, let's fix that!

is.nan.data.frame <- function(x) do.call(cbind, lapply(x, is.nan))  data123[is.nan(data123)] <- 0 
like image 64
Hong Ooi Avatar answered Oct 08 '22 01:10

Hong Ooi