+5 votes
in Programming Languages by (66.8k points)

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.

1 Answer

+3 votes
by (281k points)
selected by
Best answer

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.])