+5 votes
in Programming Languages by (71.8k points)
edited by
I have an array that contains some NaN values. I want to multiply column elements, but I am getting NaN as the answer due to NaN. How can I treat NaN as 1 while multiplying?

E.g.

[[ 1.,  2.,  3.],

 [ 4., nan,  6.],

 [ 7.,  8.,  9.],

 [10., 11., nan]]

The prod() function of Numpy returns :

>>> np.prod(aa, axis=0)

array([280.,  nan,  nan])

1 Answer

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

The nanprod() function of Numpy treats NaNs as ones. So, you can use it to get the product of array elements over a given axis.

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.nanprod(aa, axis=0)
array([280., 176., 162.])
>>> np.nanprod(aa, axis=1)
array([  6.,  24., 504., 110.])


...