How to sum the elements of an array along an axis if some of the elements are NaN? The **sum()** function of Numpy returns NaN as the answer due to NaN.

Login

0 votes

If some of the elements in the array are NaNs, you can use the** nansum()** function of Numpy. It returns the sum of array elements over a given axis treating NaNs as zeroes.

Here are examples:

>>> import numpy as np

>>> aa = np.array([[1,2,3],[4,np.nan,6],[7,8,9],[10,11,np.nan]])>>> np.nansum(aa, axis=1)

array([ 6., 10., 24., 21.])>>> np.nansum(aa, axis=0)

array([22., 21., 18.])