I have a dataset that I need to convert into a rioxarray dataset so I can use regridding features but I can't work out how to convert an already existing xarray object to rioxarray.
Unfortunately I can't just load the object in as an rioxarray object as the file is a csv that I convert from a pandas object to an xarray dataset.
df = pd.read_csv('file.csv')
df=df.set_index(["date", "latitude", "longitude"])
ds=df.to_xarray()
2 Answers 2
rio.write_crs() enables to add the coordinate reference system. Use "EPSG:4326" for standard latitude/longitude coordinates (WGS84):
import pandas as pd
import xarray as xr
import rioxarray
df = pd.read_csv('file.csv')
df = df.set_index(["date", "latitude", "longitude"])
ds = df.to_xarray()
# Convert to rioxarray by setting the CRS and spatial dimensions
ds = ds.rio.write_crs("EPSG:4326") # WGS84 lat/lon
ds = ds.rio.set_spatial_dims(x_dim="longitude", y_dim="latitude")
Comments
You can turn your existing xarray object into a rioxarray one by setting the spatial dimensions and CRS manually:
import rioxarray
from rasterio.transform import from_origin
# set spatial dims and CRS
ds = ds.rio.set_spatial_dims(x_dim="longitude", y_dim="latitude")
ds = ds.rio.write_crs("EPSG:4326")
# optional: define transform if needed
lon = ds.longitude
lat = ds.latitude
transform = from_origin(lon.min(), lat.max(),
abs(lon[1]-lon[0]), abs(lat[1]-lat[0]))
ds = ds.rio.write_transform(transform)
# now you can use rioxarray functions
ds.rio.reproject("EPSG:3857")
If your CSV points aren’t on a regular grid, you’ll need to interpolate or regrid first before using rioxarray.