Coordinate Reference System Management

Accessing the CRS object

If you have opened up a dataset and the Coordinate Reference System (CRS) is able to be determined, you can access it via the rio.crs accessor.

Search order for the CRS (DataArray and Dataset):

  1. Look in attributes (attrs) of your data array for the grid_mapping coordinate name. Inside the grid_mapping coordinate first look for spatial_ref and second for crs_wkt. This is in line with the Climate and Forecast (CF) conventions for storing the CRS.
  2. Look in the crs attribute and load in the CRS from there.

The value for the crs is anything accepted by rasterio.crs.CRS.from_user_input()

Search order for the CRS for Dataset:

If the CRS is not found using the search methods above, it also searches the data_vars and uses the first valid CRS found.

[1]:
import rioxarray
import xarray
[2]:
rds = xarray.open_dataset("../../test/test_data/input/PLANET_SCOPE_3D.nc")
[3]:
rds
[3]:
<xarray.Dataset>
Dimensions:      (time: 2, x: 10, y: 10)
Coordinates:
    spatial_ref  int64 ...
  * x            (x) float64 4.663e+05 4.663e+05 ... 4.663e+05 4.663e+05
  * time         (time) datetime64[ns] 2016-12-19T10:27:29.687763 2016-12-29T12:52:42.347451
  * y            (y) float64 8.085e+06 8.085e+06 ... 8.085e+06 8.085e+06
Data variables:
    blue         (time, y, x) float64 ...
    green        (time, y, x) float64 ...
[4]:
rds.green.attrs
[4]:
OrderedDict([('units', 'DN'),
             ('nodata', 0.0),
             ('grid_mapping', 'spatial_ref')])
[5]:
rds.spatial_ref
[5]:
<xarray.DataArray 'spatial_ref' ()>
array(0)
Coordinates:
    spatial_ref  int64 0
Attributes:
    spatial_ref:  PROJCS["WGS 84 / UTM zone 22S",GEOGCS["WGS 84",DATUM["WGS_1...
[6]:
rds.green.rio.crs
[6]:
CRS.from_epsg(32722)

Setting the CRS of the Dataset

Currently, you can use the rio.set_crs and rio.write_crs methods to set the CRS on your xarray.Dataset or xarray.DataArray.

This sets the CRS on the rio accessor without modifying the xarray.Dataset or xarray.DataArray.

[7]:
xds = xarray.DataArray(1)
xds
[7]:
<xarray.DataArray ()>
array(1)
[8]:
xds = xds.rio.set_crs(4326)
xds
[8]:
<xarray.DataArray ()>
array(1)
[9]:
xds.rio.crs
[9]:
CRS.from_epsg(4326)

This modifies the xarray.Dataset or xarray.DataArray and sets the CRS in a CF compliant manner.

[10]:
xda = xarray.DataArray(1)
xda
[10]:
<xarray.DataArray ()>
array(1)
[11]:
xda = xda.rio.write_crs(4326)
xda
[11]:
<xarray.DataArray ()>
array(1)
Coordinates:
    spatial_ref  int64 0
Attributes:
    grid_mapping:  spatial_ref
[12]:
xda.rio.crs
[12]:
CRS.from_epsg(4326)