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

Fabien Lafont lafont.fabien at gmail.com
Fri Feb 3 08:19:39 EST 2012


thx Scott!

2012/2/3 Scott Sinclair <scott.sinclair.za at gmail.com>:
> On 3 February 2012 12:48, Fabien Lafont <lafont.fabien at 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 at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user



More information about the SciPy-User mailing list