Eduardo Eduardo - 3 months ago 7
Python Question

Iterate and assign value - Python - Numpy

I´m a newbie in Python.

I´m trying to do something like this. Iterate an array, compare the value with a constant and assign values to another array.

What I´m trying to do

Thanks in advance!

Regards

Eduardo

Answer

The question needs to be more specific BTW look how the element of a numpy array are accessed and modified:

>>> # generating a random numpy array
... np_array = numpy.random.randint(0,100,10)
>>> np_array
45: array([22, 71, 40, 83, 33, 52, 29, 31, 77, 87])
>>> # Replacing 26 with 30
... np_array[np_array == 26] = 30
>>> np_array
46: array([22, 71, 40, 83, 33, 52, 29, 31, 77, 87])
>>> # multiplying all the numbers less than 50 by 10
... np_array[np_array < 50] *= 10
>>> np_array
47: array([220,  71, 400,  83, 330,  52, 290, 310,  77,  87]) 

http://docs.scipy.org/doc/numpy/user/basics.indexing.html