python - numpy piecewise function claiming lists are not same size -


i'm trying write function pass variable piecewise function, have:

def trans(a):     np.piecewise(a, [(a<.05) & (a>=0),                     (a<.1) & (a>= .05),                     (a<.2) & (a>=.1),                     (a<.4) & (a>=.2),                     (a<1) & (a>=.4)],                     [0,1,2,3,4]) 

however, when run trans(a), get:

valueerror: function list , condition list must same

the function , condition list used both length 5, i'm not sure issue is

edit: apparently numpy.piecewise expects array, needed pass one, instead of plain variable?

that's error you'd if a list , not ndarray:

>>> = [1,2,7] >>> np.piecewise(a, [a == 1, > 1, > 4], [lambda x: 100*x, lambda x: x**2, lambda x: x]) traceback (most recent call last):   file "<ipython-input-18-03e300b14962>", line 1, in <module>     np.piecewise(a, [a == 1, > 1, > 4], [lambda x: 100*x, lambda x: x**2, lambda x: x])   file "/usr/local/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 693, in piecewise     "function list , condition list must same") valueerror: function list , condition list must same  >>> = np.array(a) >>> np.piecewise(a, [a == 1, > 1, > 4], [lambda x: 100*x, lambda x: x**2, lambda x: x]) array([100,   4,   7]) 

this happens because if a list, vector comparisons don't behave intended:

>>> = [1,2,7] >>> [a == 1, > 1, > 4] [false, true, true] 

and these lines lines in np.piecewise

if isscalar(condlist) or \        not (isinstance(condlist[0], list) or             isinstance(condlist[0], ndarray)):     condlist = [condlist] condlist = [asarray(c, dtype=bool) c in condlist] 

mean you'll wind thinking condition list looks like

[array([false,  true,  true], dtype=bool)] 

which list of length 1.

[oops-- noticed conditions weren't mutually exclusive. oh, well, doesn't matter explaining what's going on anyway.]


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -