Why does the sum () operation on numpy masked_array change the fill value to 1e20?

Is this a sign or a mistake? Can someone explain to me this numpy masked_array behavior? It seems that the fill_value value has changed after applying the sum operation, which is confusing if you intend to use a filled result.

data=ones((5,5)) m=zeros((5,5),dtype=bool) """Mask out row 3""" m[3,:]=True arr=ma.masked_array(data,mask=m,fill_value=nan) print arr print 'Fill value:', arr.fill_value print arr.filled() farr=arr.sum(axis=1) print farr print 'Fill value:', farr.fill_value print farr.filled() """I was expecting this""" print nansum(arr.filled(),axis=1) 

Print output:

 [[1.0 1.0 1.0 1.0 1.0] [1.0 1.0 1.0 1.0 1.0] [1.0 1.0 1.0 1.0 1.0] [-- -- -- -- --] [1.0 1.0 1.0 1.0 1.0]] Fill value: nan [[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ nan nan nan nan nan] [ 1. 1. 1. 1. 1.]] [5.0 5.0 5.0 -- 5.0] Fill value: 1e+20 [ 5.00000000e+00 5.00000000e+00 5.00000000e+00 1.00000000e+20 5.00000000e+00] [ 5. 5. 5. nan 5.] 
+8
python numpy
source share
1 answer

The array returned by arr.sum is a new array that does not inherit the fill_value arr value (although I agree that this could be a good improvement to np.ma ). As a workaround you can use

 In [18]: farr.filled(arr.fill_value) Out[18]: array([ 5., 5., 5., nan, 5.]) 
+2
source share

All Articles