i experiencing weird behaviour when using numpy.nan can't understand. here minimal example:
from numpy import nan def _bool3key(x): """ defines keys used order list. allowed values true, false, 1,0 , numpy.nan. """ return _bool3key.__logic_sort__[x] _bool3key.__logic_sort__ = {0:-1, nan:0 , 1:1} def and3(*args): return min(*args,key=_bool3key) def f(x): """long function produces in output vector containing 0, nan , 1s. pass #
sometimes and3 function fails, despite in vector returned f(x) there 0, nan, or 1 values: reason nan not of type numpy.nan...
for example v = f(x)
produced vector [nan,nan]
. if try type: v[0] nan
false
(which causes and3 not work); weird thing though v[1] nan
true
.
what causing behaviour? how can correctly use nan value in and3
function??
if use
_bool3key.__logic_sort__ = {0:-1, nan:0 , 1:1}
then 1 problem might run float('nan')
not recognized same key np.nan
:
in [17]: _bool3key(float('nan')) keyerror: nan
here workaround:
def _bool3key(x, logic_sort={0: -1, 1: 1}): """ defines keys used order list. allowed values true, false, 1,0 , nan. """ return 0 if np.isnan(x) else logic_sort[x]
also, attribute lookups slower local variable lookups, you'll better performance defining logic_sort
default parameter making function attribute. don't have define outside of function, , little easier read too.
Comments
Post a Comment