Skip to content

Instantly share code, notes, and snippets.

@mathause
Created August 2, 2023 12:10
Show Gist options
  • Save mathause/53a3f77bf264e1b1eb41f204b8f08a4a to your computer and use it in GitHub Desktop.
Save mathause/53a3f77bf264e1b1eb41f204b8f08a4a to your computer and use it in GitHub Desktop.
wrap longitude to 180/ 360
import numpy as np
def wrap360(obj, lon='lon'):
"""
wrap longitude coordinates to 0..360
Parameters
----------
obj : xr.Dataset or xr.DataArray
object with longitude coordinates
lon : str, default: "lon"
name of the longitude ('lon', 'longitude', ...)
Returns
-------
wrapped : Dataset
Another dataset array wrapped around.
"""
# wrap -180..179 to 0..359
new_lon = np.mod(obj[lon], 360)
obj = obj.assign_coords(**{lon: new_lon})
# sort the data
return obj.reindex(**{lon : np.sort(obj[lon])})
def wrap180(obj, lon='lon'):
"""
wrap longitude coordinates to -180..180
Parameters
----------
obj : xr.Dataset or xr.DataArray
object with longitude coordinates
lon : str, default: "lon"
name of the longitude ('lon', 'longitude', ...)
Returns
-------
wrapped : Dataset
Another dataset array wrapped around.
"""
# wrap 0..359 to -180..179
new_lon = obj[lon].data
# only modify values > 180
sel = new_lon > 180
if np.any(sel):
# 359 -> -1, 181 -> -179
new_lon[sel] = np.mod(new_lon[sel], -180)
obj = obj.assign_coords(**{lon: new_lon})
# sort the data
obj = obj.reindex(**{lon : np.sort(obj[lon])})
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment