[Tutor] change values in an array

Peter Otten __peter__ at web.de
Thu Nov 17 09:21:29 CET 2011


questions anon wrote:

> I am trying to do something really simple.
> I have a numpy array and if any values in the array are 255 I want to
> change them to 1.
> but I can't seem to get anything to work!

Note that numpy is a specialist topic, and for everything but the basics the 
numpy mailing list is the best place to ask questions about it.
> 
> If I use:
> 
> for i, value in enumerate(mask_arr):
>     if value==255:
>         mask_arr[i]=1
> 
> I get this error:
> 
> Traceback (most recent call last):
>   File "d:/timeseries_mask.py", line 51, in <module>
>     if value==255:
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()
> 
> and if I try to add a.any() to my code:
> 
> for i, value in enumerate(mask_arr):
>     if value.any()==255:
>         mask_arr[i]=1
> 
> my array does not change at all.
> Any feedback will be greatly appreciated

You seem to have a multidimensional array, i. e. value is still an array

>>> import numpy
>>> a = numpy.array([[1, 2], [3, 4]])
>>> for value in a: print value
...
[1 2]
[3 4]
>>> if a[0]: pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

If you want to access the values of an n-dimensional array using a standard 
Python approach you have to use n nested for-loops:

>>> for i, row in enumerate(a):
...     for k, value in enumerate(row):
...             if value == 1:
...                     a[i, k] = 42
...
>>> a
array([[42,  2],
       [ 3,  4]])

As that is not very efficient numpy offers an alternative:

>>> a[a == 42] = 123
>>> a
array([[123,   2],
       [  3,   4]])

or using the names from your example:

mask_arr[mask_arr == 255] = 1





More information about the Tutor mailing list