Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum NaN in numpy?

Tags:

python

numpy

I have to sum two values obtained by np.average as

for i in x :
    a1 = np.average(function1(i))
    a2 = np.average(function2(i))
    plt.plot(i, a1+a2, 'o')

But the np.average may return NaN. Then, only points for which both a1 and a2 are available will be calculated.

How can I use zero instead of NaN to make the sum for all points?

I tried to find a function in numpy to do so, but numpy.nan_to_num is for arrays.

like image 412
Googlebot Avatar asked Jan 03 '23 11:01

Googlebot


2 Answers

You can use numpy like this:

import numpy as np

a = [1, 2, np.nan]
a_sum = np.nansum(a)
a_mean = np.nanmean(a)

print('a = ', a) # [1, 2, nan]
print("a_sum = {}".format(a_sum)) # 3.0
print("a_mean = {}".format(a_mean)) # 1.5
like image 76
BhishanPoudel Avatar answered Jan 16 '23 03:01

BhishanPoudel


You can also use :

clean_x = x[~np.isnan(x)]
like image 28
Ashlou Avatar answered Jan 16 '23 03:01

Ashlou