Skip to content

Commit e110dff

Browse files
committed
Add .cf.crs attribute
1 parent c511cc5 commit e110dff

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

cf_xarray/accessor.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from collections.abc import Hashable, Iterable, Mapping, MutableMapping, Sequence
99
from datetime import datetime
1010
from typing import (
11+
TYPE_CHECKING,
1112
Any,
1213
Callable,
1314
Literal,
@@ -57,6 +58,9 @@
5758
parse_cf_standard_name_table,
5859
)
5960

61+
if TYPE_CHECKING:
62+
from pyproj import CRS
63+
6064
FlagParam = namedtuple("FlagParam", ["flag_mask", "flag_value"])
6165

6266
#: Classes wrapped by cf_xarray.
@@ -2342,6 +2346,19 @@ def __getitem__(self, key: Hashable | Iterable[Hashable]) -> DataArray | Dataset
23422346
"""
23432347
return _getitem(self, key)
23442348

2349+
@property
2350+
def crs(self) -> CRS:
2351+
from pyproj import CRS
2352+
2353+
try:
2354+
gm = self["grid_mapping"]
2355+
except KeyError as e:
2356+
raise ValueError(
2357+
"CRS is constructed from the 'grid_mapping' variable, but that could not be detected."
2358+
) from e
2359+
2360+
return CRS.from_cf(gm.attrs)
2361+
23452362
@property
23462363
def formula_terms(self) -> dict[Hashable, dict[str, str]]: # numpydoc ignore=SS06
23472364
"""

doc/api.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ Attributes
4545
DataArray.cf.cell_measures
4646
DataArray.cf.cf_roles
4747
DataArray.cf.coordinates
48+
DataArray.cf.crs
4849
DataArray.cf.formula_terms
4950
DataArray.cf.grid_mapping_name
5051
DataArray.cf.is_flag_variable
@@ -103,6 +104,7 @@ Attributes
103104
Dataset.cf.bounds
104105
Dataset.cf.cell_measures
105106
Dataset.cf.cf_roles
107+
Dataset.cf.crs
106108
Dataset.cf.coordinates
107109
Dataset.cf.formula_terms
108110
Dataset.cf.grid_mapping_names

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ module=[
139139
"pandas",
140140
"pooch",
141141
"pint",
142+
"pyproj",
142143
"matplotlib",
143144
"pytest",
144145
"shapely",

0 commit comments

Comments
 (0)