norm.campbell
norm.campbell

Reputation: 1

changing int band values to names

I have the contents of an xarray.DataArray, geotiffs_da, formed by reading data from several geoTIFF files. Some of the xarray content is as follows:

geotiffs_da_renamed <xarray.DataArray (time: 10, band: 9, latitude: 101, longitude: 101)> array([[[[1065., 1041., 1036., ..., 1069., 1025., 1028.], ... [4342., 4192., 4022., ..., 3468., 3458., 3469.]]]], dtype=float32) Coordinates:

The original xarray had 'x' and 'y' in place of longitude and latitude, and I was able to change these using

geotiffs_da = geotiffs_da.rename ( { 'x': 'longitude', 'y': 'latitude' } )

How do I change the contents of 'band' so that it shows blue, green, red, ..., rather than 1, 2, 3, ...?

Upvotes: 0

Views: 532

Answers (1)

Luke
Luke

Reputation: 80

assign_coords() will do this. Documentation is here

Here is an example:

import xarray as xr
import pandas as pd

#============================
# create sample dataset (ds)
#============================
# create dataFrame
df = pd.DataFrame({'x':[1,2,3,4,5,6,7],
                   'y':[10,20,30,40,50,60,70]}).set_index('x')

# convert to dataset
ds = df.to_xarray()

#============================
# assign new x coordinate
# to list of colors
#============================
ds = ds.assign_coords(x=['red','orange','yellow','green','blue','indigo','violet'])

ds.assign_coords(x=...) assigns the coordinate x to the list of colors. Since Xarray always returns an object and doesn't have an inplace=True option like Pandas, we have to either replace the original dataset (ds) or assign it to something else.

Upvotes: 0

Related Questions