Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Python Numpy arrays (rasters converted to 2D arrays, specifically) and what I want to do is take one array that has arbitrary dummy values of -999 representing "no data" and I want to replace those values with the corresponding "real" values from a different array of the same size and shape in the correct location. I couldn't find a very similar question to this but note that I am a novice with Python and Numpy.

But what I want to do is this:

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 in 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 really want to change the shape or dimensions of the array because I am going to convert back out into a raster afterwards so I need the correct values in the correct locations. What is the best way to do this?

like image 282
Matt Avatar asked Apr 24 '17 14:04

Matt


2 Answers

Just do boolean masking:

mask = (array_a == -999)
new_array = np.copy(array_a)
new_array[mask] = array_b[mask]
like image 168
Hannes Ovrén Avatar answered Sep 20 '22 14:09

Hannes Ovrén


all you need to do is

array_a[array_a==-999]=array_b[array_a==-999]

we are putting boolean condition on array elements to update should have value -999

import numpy as np
array_a =np.array([[0.564,-999,-999],
 [0.234,-999,0.898],
 [-999,0.124,0.687], [![enter image description here][1]][1]
 [0.478,0.786,-999]])

array_b =np.array([[0.324,0.254,0.204],
 [0.469,0.381,0.292],
 [0.550,0.453,0.349], 
 [0.605,0.582,0.551]])
array_a[array_a==-999]=array_b[array_a==-999]

run this snippet

[1]: https://i.stack.imgur.com/oRdsE.png

like image 42
PRAVENDRA S KHINCHI B16EE026 Avatar answered Sep 20 '22 14:09

PRAVENDRA S KHINCHI B16EE026