Messak
Messak

Reputation: 463

modify an xarray column with a calculation

This seems like it should be pretty straight forward, but perhaps my inexperience with arrays is making it difficult for me. I have an xarray enter image description here

what i am trying to do is multiply the band column by something along the lines of

ds[:, 0] = (ds[:, 0] - xmin) / (xmax - xmin)

where

xmin is -0.21
xmax is 0.3

the line above does not seem to work as expected. it seems to modify the nodata values. I also tried

 ds2 = ds.where(ds.band > -10000.0)

then ran the line, with different but still incorrect results.

the xmin and xmax are not related to the XY data, the raster that I am reading into an array has XYZ data, what I am trying to do is normalize the Z(elevation) column, which I think is displayed as "band" in the image. The xmin and xmax are actually the minimum and maximum Z value of several rasters/arrays that I will be comparing.

So I don't want to modify the XY only the Z. After words, I will be re-exporting the array back into a raster

So for the entire column adjust each value with the above formula

I'm sure this is a very easy task, but i can not figure out how to do this.

Upvotes: 1

Views: 421

Answers (1)

Val
Val

Reputation: 7033

You have a 3d DataArray, but the band dimension is only 1, so you basically have a 2d array. You can use ds.squeeze() to drop the dimension if you don’t need / want it.

When you say

what i am trying to do is multiply the band column

do you mean applying the multiplication to the whole array (so to each pixel)?

In that case, you can do:

xmin = -0.21
xmax = 0.3

ds_scaled = (ds - xmin) / (xmax - xmin)

Since it looks like you want to scale/normalize the data, you can also use xmin and xmax derived from the data:


# over full array
xmin = ds.min()
xmax = ds.max()

ds_scaled = (ds - xmin) / (xmax - xmin)

or just over as specific dimension


# over y dimension
xmin = ds.min(‘y’)
xmax = ds.max(‘y’)

ds_scaled = (ds - xmin) / (xmax - xmin)

Upvotes: 2

Related Questions