Skip to content

Commit

Permalink
Add xarray_to_raster function (#827)
Browse files Browse the repository at this point in the history
  • Loading branch information
giswqs authored Jul 14, 2024
1 parent 01cf99e commit 1bff90d
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions leafmap/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -13976,3 +13976,41 @@ def remove_port(match):
result = url_with_port_pattern.sub(remove_port, data)

return result


def xarray_to_raster(dataset, filename: str, **kwargs: Dict[str, Any]) -> None:
"""Convert an xarray Dataset to a raster file.
Args:
dataset (xr.Dataset): The input xarray Dataset to be converted.
filename (str): The output filename for the raster file.
**kwargs (Dict[str, Any]): Additional keyword arguments passed to the `rio.to_raster()` method.
See https://corteva.github.io/rioxarray/stable/examples/convert_to_raster.html for more info.
Returns:
None
"""
import rioxarray

dims = list(dataset.dims)

new_names = {}

if "lat" in dims:
new_names["lat"] = "y"
dims.remove("lat")
if "lon" in dims:
new_names["lon"] = "x"
dims.remove("lon")
if "lng" in dims:
new_names["lng"] = "x"
dims.remove("lng")
if "latitude" in dims:
new_names["latitude"] = "y"
dims.remove("latitude")
if "longitude" in dims:
new_names["longitude"] = "x"
dims.remove("longitude")

dataset = dataset.rename(new_names)
dataset.transpose(..., "y", "x").rio.to_raster(filename, **kwargs)

0 comments on commit 1bff90d

Please sign in to comment.