Example - Convert dataset to raster (GeoTiff)

Often, it is desirable to take a variable (band) out of your dataset and export it to a raster. This is possible with the rio.to_raster()method. It does most of the work for you so you don’t have to.

Note: The rio.to_raster() method only works on a 2-dimensional or 3-dimensional xarray.DataArray or a 2-dimensional xarray.Dataset.

API Reference:

[1]:
import rioxarray

See docs for rioxarray.open_rasterio

[2]:
rds = rioxarray.open_rasterio(
    "../../test/test_data/input/PLANET_SCOPE_3D.nc",
)
rds
[2]:
<xarray.Dataset>
Dimensions:      (time: 2, x: 10, y: 10)
Coordinates:
  * y            (y) float64 8.085e+06 8.085e+06 ... 8.085e+06 8.085e+06
  * x            (x) float64 4.663e+05 4.663e+05 ... 4.663e+05 4.663e+05
  * time         (time) object 2016-12-19 10:27:29 2016-12-29 12:52:41.659696
    spatial_ref  int64 0
Data variables:
    blue         (time, y, x) float64 ...
    green        (time, y, x) float64 ...
Attributes:
    coordinates:  spatial_ref

Converting Dataset to raster

Dataset: rio.to_raster()

[3]:
# note how one time slice was selected on export to make the dataset 2D
rds.isel(time=0).rio.to_raster("planet_scope.tif")
[4]:
!rio info planet_scope.tif
{"bounds": [466266.0, 8084670.0, 466296.0, 8084700.0], "colorinterp": ["gray", "undefined"], "count": 2, "crs": "EPSG:32722", "descriptions": ["blue", "green"], "driver": "GTiff", "dtype": "float64", "height": 10, "indexes": [1, 2], "interleave": "pixel", "lnglat": [-51.31732641226951, -17.322997474192466], "mask_flags": [["nodata"], ["nodata"]], "nodata": NaN, "res": [3.0, 3.0], "shape": [10, 10], "tiled": false, "transform": [3.0, 0.0, 466266.0, 0.0, -3.0, 8084700.0, 0.0, 0.0, 1.0], "units": [null, null], "width": 10}

Converting DataArray to raster

DataArray: rio.to_raster()

[5]:
# note how selecting one variable allowed for multiple time steps in a single raster
rds.green.rio.to_raster("planet_scope_green.tif")
[6]:
!rio info planet_scope_green.tif
{"bounds": [466266.0, 8084670.0, 466296.0, 8084700.0], "colorinterp": ["gray", "undefined"], "count": 2, "crs": "EPSG:32722", "descriptions": ["green", "green"], "driver": "GTiff", "dtype": "float64", "height": 10, "indexes": [1, 2], "interleave": "pixel", "lnglat": [-51.31732641226951, -17.322997474192466], "mask_flags": [["nodata"], ["nodata"]], "nodata": NaN, "res": [3.0, 3.0], "shape": [10, 10], "tiled": false, "transform": [3.0, 0.0, 466266.0, 0.0, -3.0, 8084700.0, 0.0, 0.0, 1.0], "units": [null, null], "width": 10}