[SciPy-User] [scipy-user] How to apply a condition on some specific values of an array

Scott Sinclair scott.sinclair.za@gmail....
Mon Feb 6 04:13:32 CST 2012


On 6 February 2012 11:41, Fabien Lafont <lafont.fabien@gmail.com> wrote:
> And is it possible to apply a specific operation with a condition
> (if). I have to apply different operations on the same array depending
> on the value of the array element.
>
> For example: I have an array like that:
>
> [100  250  501  700] and I want to multiply by 100 the value if this
> value is smalest thant 500 and multiply by 1000 if the value is
> bigest.

Here's one way that should be easy to follow. You'll have to make a
copy of your array (as shown here), or generate two index arrays
before modifying your original array.

In [1]: arr = np.array([100, 250, 501, 700])

In [2]: # make a copy to avoid aliasing
   ...: new_arr = np.array(arr)

In [3]: new_arr[arr < 500] *= 100

In [4]: new_arr[arr > 500] *= 1000

In [5]: arr
Out[5]: array([100, 250, 501, 700])

In [6]: new_arr
Out[6]: array([ 10000,  25000, 501000, 700000])

Cheers,
Scott


More information about the SciPy-User mailing list