Numpy max function does not work when using decimal values โ€‹โ€‹that include NaN

Everything is fine when you work with float values.

>>> import numpy as np
>>> np.max(1.2, np.nan)
>>> nan

But when working with decimal values โ€‹โ€‹...

>>> import numpy as np
>>> import decimal as d 
>>> np.max([d.Decimal('1.2'), d.Decimal('NaN')])
>>> InvalidOperation: comparison involving NaN

Is there a way to get decimal values โ€‹โ€‹with NaN to play nicely?

Note:

  • Python 2.7
  • Numpy 1.6.2
+4
source share
2 answers

Hum ... if there is at least one NaN, the result will be NaN.

Wrapper in function:

def my_max(arr):
    try:
        return np.max(arr)
    except d.InvalidOperation:
        return d.Decimal('NaN')

Not very sexy though ...


An alternative ... maybe ... as Decimalit allows you to "disable" some exceptions by returning a value instead of throwing an exception
# change globally
>>> d.getcontext().traps[d.InvalidOperation] = 0
>>> np.max([d.Decimal('1.2'), d.Decimal('NaN')])
Decimal('NaN')


# use a context manager to change locally:
with d.localcontext() as ctx:
    ctx.traps[d.InvalidOperation] = 0
    np.max([d.Decimal('1.2'), d.Decimal('NaN')])
+4
source

NumPy float. NumPy :

import numpy as np
import decimal as d

print np.max(np.array([0, 1, d.Decimal('nan')], dtype='float'))
print np.nanmax(np.array([0, 1, d.Decimal('nan')], dtype='float'))

:

nan
1.0
+1

All Articles