quickly looping over a 2D array?
Peter Otten
__peter__ at web.de
Mon Jul 27 15:17:58 CEST 2009
Martin wrote:
> On Jul 27, 1:46 pm, Peter Otten <__pete... at web.de> wrote:
>> Martin wrote:
>> > On Jul 27, 12:42 pm, Peter Otten <__pete... at web.de> wrote:
>> >> Martin wrote:
>> >> > I am new to python and I was wondering if there was a way to speed
>> >> > up the way I index 2D arrays when I need to check two arrays
>> >> > simultaneously? My current implementations is (using numpy)
>> >> > something like the following...
>>
>> >> > for i in range(numrows):
>> >> > for j in range(numcols):
>>
>> >> > if array_1[i, j] == some_value or array_2[i, j] >=
>> >> > array_1[i,
>> >> > j] * some_other_value
>> >> > array_1[i, j] = some_new_value
>>
>> >> array_1[(array_1 == some_value) | (array_2 >= array_1 *
>> >> some_other_value)] = some_new_value
>>
>> >> maybe?
>>
>> > So I tried...
>>
>> > band_1[(array_1 == 255) or (array_2 >= array_1 * factor)] = 0
>>
>> > which led to
>>
>> > ValueError: The truth value of an array with more than one element is
>> > ambiguous. Use a.any() or a.all()
>>
>> > so not sure that works?
>>
>> Copy and paste -- or replace "or" with "|".
>
> apologies - I mistook that for a type for "or"
>
> I now get the following error...
>
> ValueError: shape mismatch: objects cannot be broadcast to a single
> shape
It seems array_1 and array_2 have a -- dada! -- different shape.
Assuming array_1 is the smaller one:
numrows, numcols = array_1.shape
array_1[(array_1 == some_value) | (array_2[:numrows,:numcols] >= array_1 *
some_other_value)] = some_new_value
There may be other options, but I'm not a numpy expert.
Peter
More information about the Python-list
mailing list