Supernova
Supernova

Reputation: 99

How to opperate each cell of 2D array/matrix?

Hi I'm reading two rasters A & B as arrays.

What I'm looking for is to make an opperation to certain cells within two 2D arrays (two rasters). I need to subtract -3.0 to the cells in one array (A) that are greater than the other cells within the 2D array (B).

All the other cells don't need to change, so my answer will be the 2D array (B) with some changed cells that fit that condition and the other 2D array (A) untouched.

I tried this but doesn't seem to work (also takes TOO long):

A = Raster_A.GetRasterBand(1).ReadAsArray()
B = Raster_B.GetRasterBand(1).ReadAsArray()

A = array([ 917.985028, 916.284480, 918.525323, 920.709505,
            921.835315, 922.328555, 920.283029, 922.229594,
            922.928670, 925.315534, 922.280360, 922.715303,
            925.933969, 925.897328, 923.880606, 923.864701])

B = array([ 913.75785758,  914.45941854,  915.17586919,  915.90724705,
            916.6534542 ,  917.4143068 ,  918.18957846,  918.97902532,
            919.78239295,  920.59941086,  921.42978108,  922.27316565,
            923.12917544,  923.99736194,  924.87721232,  925.76814782])

for i in np.nditer(A, op_flags=['readwrite']):
    for j in np.nditer(B, op_flags=['readwrite']):
        if j[...] > i[...]:
            B = j[...]-3.0

So the answer, the array B should be something like:

B = array([ 913.75785758,  914.45941854,  915.17586919,  915.90724705,
            916.6534542 ,  917.4143068 ,  918.18957846,  918.97902532,
            919.78239295,  920.59941086,  921.42978108,  922.27316565,
            923.12917544,  923.99736194,  921.87721232,  922.76814782]) 

Please notice the two bottom right values :)

I'm a bit dizzy already from trying and doing other stuff at the same time so I apologize if I did any stupidity right there, any suggestion is greatly appreciated. Thanks!

Upvotes: 0

Views: 83

Answers (1)

Samufi
Samufi

Reputation: 2710

Based on your example, I conclude that you want to subtract values from the array B. This can be done via

B[A<B] -= 3

The "mask" A<B is a boolean array that is true at all the values that you want to change. Now, B[A<B] returns a view to exactly these values. Finally, B[A<B] -= 3 changes all these values in place.

It is crucial that you use the inplace operator -=, because otherwise a new array will be created that contain only the values where A<B. Thereby, the array is flattened, i.e. looses its shape, and you do not want that.

Regarding speed, avoid for loops as much as you can when working with numpy. Fancy indexing and slicing offers you very neat (and super fast) options to work with your data. Maybe have a look here and here.

Upvotes: 1

Related Questions