python - How to apply multiple functions to numpy array? -


i know how vectorize() or apply function along axis .. case bit different. have 1d array (z) contains 1 or 0 , have 2d array (x). want apply 2 different functions every row in array-x depending on value row in array-z.

if 0 apply fun0() if 1 apply fun1() 

i can build index , apply index, :

ndx1 = (z == 1) ndx0 = (z == 0) 

and f.e.:

fun(x[:,ndx]) 

but wont change array-x. need modified array-x further calculations.

how ? (somehow inplace modification ?) love if there function takes array of functions , applies array :) way wont need inplace modifications ?

thank you..

slicing numpy array gives view same data. if change values there, change values in original:

>>> = np.array([1,2,0,0,1,4]) >>> array([1, 2, 0, 0, 1, 4]) >>> a[a == 0] = 5 >>> array([1, 2, 5, 5, 1, 4]) 

so want like

x[x == 0] = fun0(x[x == 0]) x[x == 1] = fun1(x[x == 1]) 

a possible problem doing these in sequence fun0 might return 1 values. so, fun0 gets applied , produces 1, , fun1 gets applied.

if it's not terribly important function vectorized, might consider doing like:

>>> def myfun(x_val): ...     return fun0(x_val) if x_val == 0 else fun1(x_val) ... >>> x = np.array(map(myfun,x)) 

Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -