+4 votes
in Programming Languages by (17.7k 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

0 votes
by (35.8k points)

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

...