Python Numpy: replace values ​​in one array with corresponding values ​​in another array

I am using Python Numpy arrays (specifically rasters converted to 2D arrays) and I want to make one array with arbitrary values ​​-999 representing "no data" and I want to replace those values ​​with the corresponding "real" values ​​from another an array of the same size and shape in the correct location. I couldn't find a very similar question, but note that I'm new to Python and Numpy.

But I want to do the following:

array_a = 
([[0.564,-999,-999],
 [0.234,-999,0.898],
 [-999,0.124,0.687], 
 [0.478,0.786,-999]])

array_b = 
([[0.324,0.254,0.204],
 [0.469,0.381,0.292],
 [0.550,0.453,0.349], 
 [0.605,0.582,0.551]])

      

use the values ​​of array_b to fill the -999 values ​​in array_a and create a new array:

new_array_a = 
([[0.564,0.254,0.204],
 [0.234,0.381,0.898],
 [0.550,0.124,0.687], 
 [0.478,0.786,0.551]])

      

I don't want to change the shape or dimensions of the array, because after that I will convert back to raster, so I need the correct values ​​in the correct places. What's the best way to do this?

+3


source to share


1 answer


Just do logical masking:



mask = (array_a == -999)
new_array = np.copy(array_a)
new_array[mask] = array_b[mask]

      

+6


source







All Articles