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

Fabien Lafont lafont.fabien@gmail....
Mon Feb 6 03:41:20 CST 2012


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.

Fabien

2012/2/3 Fabien Lafont <lafont.fabien@gmail.com>:
> thx Scott!
>
> 2012/2/3 Scott Sinclair <scott.sinclair.za@gmail.com>:
>> On 3 February 2012 12:48, Fabien Lafont <lafont.fabien@gmail.com> wrote:
>>> I'm just starting to use numpy and I have still Python's reflexes so I
>>> want to know how can I do the following code using Numpy "style".
>>>
>>> for i in range(0,len(array)+1):
>>>       if 10<array[i]<100:
>>>            new_array = array[i]*1000
>>>
>>> In other words is it possible to "scan" the values of an array and
>>> apply a "modification" to it if the condition is true
>>
>> Yes - you can use fancy indexing (see
>> http://docs.scipy.org/doc/numpy/user/basics.indexing.html)
>>
>> In[1]: import numpy as np
>>
>> In[2]: arr = np.arange(10)
>> In[3]: arr
>> Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>
>> In[4]: arr[(2 < arr) & (arr < 9)] *= 1000
>> In[5]: arr
>> Out[5]: array([   0,    1,    2, 3000, 4000, 5000, 6000, 7000, 8000,    9])
>>
>> Cheers,
>> Scott
>> _______________________________________________
>> SciPy-User mailing list
>> SciPy-User@scipy.org
>> http://mail.scipy.org/mailman/listinfo/scipy-user


More information about the SciPy-User mailing list