sten
sten

Reputation: 7476

How to apply multiple functions to numpy array?

I know how to vectorize() or apply function along axis .. but my case is a bit different. I have 1D array (z) that contains 1 or 0 and then I have a 2D array (x). I want to apply two different functions for every row in array-x depending on the value for this row in array-z.

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

I can also build an index and then apply by index, like this :

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

and do f.e.:

fun(x[:,ndx])

but this wont change the array-x. I would need this modified array-x for further calculations.

How would I do that ? (Somehow do inplace modification ?) I would love if there is also a function that takes an array of functions and applies it to another array :) this way I probably wont need to do inplace modifications ?

thank you..

Upvotes: 2

Views: 2438

Answers (2)

bgschiller
bgschiller

Reputation: 2127

Slicing a numpy array gives you another view into the same data. So if you change it the values there, you change the values in the original:

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

so what you want is something like

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

A possible problem with doing these in sequence is that fun0 might return 1 for some values. So, fun0 gets applied and produces 1, and then fun1 gets applied.

If it's not terribly important that the function be vectorized, you might consider doing something like:

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

Upvotes: 2

hpaulj
hpaulj

Reputation: 231335

Is the kind of action that you want?

In [19]: x=np.arange(12,dtype=float).reshape(4,3)

In [20]: z=np.array([0,1,0,1])

In [21]: I=(z==1)

In [22]: x[I,:]=x[I,:]*.1

In [23]: x
Out[23]: 
array([[ 0. ,  1. ,  2. ],
       [ 0.3,  0.4,  0.5],
       [ 6. ,  7. ,  8. ],
       [ 0.9,  1. ,  1.1]])

Row (or column) indexing (here with a boolean I) can be used on both sides of the equation, both for selecting rows to use, and rows to over write.

Upvotes: 2

Related Questions