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

Scott Sinclair scott.sinclair.za@gmail....
Fri Feb 3 05:29:49 CST 2012


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


More information about the SciPy-User mailing list