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):¶
- Look in attributes (
attrs
) of your data array for thegrid_mapping
coordinate name. Inside thegrid_mapping
coordinate first look forspatial_ref
thencrs_wkt
and lastly the CF grid mapping attributes. This is in line with the Climate and Forecast (CF) conventions for storing the CRS as well as GDAL netCDF conventions. - Look in the
crs
attribute and load in the CRS from there. This is for backwards compatibility withxarray.open_rasterio
. We recommend usingrioxarray.open_rasterio
instead.
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.
API Documentation¶
[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)