0

I am summing arrays containing nan values by using:

for i in range(whatever):
    a = *something different at each cycle*
    b = np.nansum([b, a],axis=0)

#now calculate the average of b elements avoiding nan counts

(b and a being of the same size). Now, as you can see, this is iterative, adding the elements to create at the end one single sum-array.

At the end, I would like to calculate the average for each of the elements of the final b array, excluding the nan elements from the count, of course.

All the other discussions I found only take in account two arrays, and the average of their elements is obtained by using nanmean, but this is not possible here, I think.

Possibly, I could also change the way to sum the elements, if nansum is not the best way, but this is how I did it until now.

So, is there a simple way to obtain the final average excluding nan elements from the count?

EDIT: the iteration is made several times, not just one, using a array (in the example) changing in each cycle. This is why I am not able to use the same solution as in the linked question

Community
  • 1
  • 1
Py-ser
  • 1,860
  • 9
  • 32
  • 58
  • In that case the OP do not sum iteratively. Or, I don't know how to reduce the two cases to the same solution. – Py-ser May 14 '14 at 08:53
  • You can't simply keep track of the number of NaNs in a, take the sum of b after the loop and divide by the total number of non-NaN elements (`len(whatever) * a.size - totalNaNs`)? –  May 14 '14 at 09:47

1 Answers1

0

You could keep track of the number of non-nan elements yourself

n = np.zeros(*shape of a*)
for i in range(whatever):
    a = *something different at each cycle*
    b = np.nansum([b, a],axis=0)
    n = np.sum([n, np.invert(np.isnan(a))],axis=0)

avg = b/n
user3419537
  • 4,740
  • 2
  • 24
  • 42
  • this can not work. This returns a number, while I need an array of the summation of nan for each element position. – Py-ser May 15 '14 at 01:02
  • You are right, I had misinterpreted what you were trying to do. I've updated my answer to do what you want. – user3419537 May 15 '14 at 09:28