Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add xarray_to_raster function #827

Merged
merged 1 commit into from
Jul 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading