Ensuring compatibility between nums 1.8 and nansum 1.9?

I have a code that must behave the same regardless of the version of numpy, but the basic function is np.nansumto change the behavior, so that np.nansum([np.nan,np.nan])- 0.0in 1.9 and NaN1.8. The behavior <= 1.8 is the one I would prefer, but it is even more important that my code is resistant to the numpy version.

The difficulty is that the code applies an arbitrary numpy function (usually a function np.nan[something]) to ndarray. Is there a way to make the new or old numpy function nan[something]match the old or new behavior shy of monkeypatching?

The possible solution that I can think of is something like outarr[np.allnan(inarr, axis=axis)] = np.nan, but there is no function np.allnan- if this is the best solution, this is the best implementation np.all(np.isnan(arr), axis=axis)(for which only np> = 1.7 support is required, but this is probably OK)?

+4
source share
1 answer

In Numpy 1.8, it nansumwas defined as:

a, mask = _replace_nan(a, 0)

if mask is None:
    return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
mask = np.all(mask, axis=axis, keepdims=keepdims)
tot = np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
if np.any(mask):
    tot = _copyto(tot, np.nan, mask)
    warnings.warn("In Numpy 1.9 the sum along empty slices will be zero.",
                  FutureWarning)
return tot

In Numpy 1.9, this is:

a, mask = _replace_nan(a, 0)
return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)

I don’t think there is a way to make the new one nansumbehave the same way, but considering that the source code is nansumnot so long, can you just include a copy of this code (without warning) if you care about keeping the behavior up to 1.8.

Please note that _copytoyou can importnumpy.lib.nanfunctions

+1
source

All Articles