Skip to content

Commit a20f8ba

Browse files
committed
add skip to rename_like
1 parent 9e86af8 commit a20f8ba

File tree

3 files changed

+30
-12
lines changed

3 files changed

+30
-12
lines changed

cf_xarray/accessor.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
List,
1313
Mapping,
1414
MutableMapping,
15+
Optional,
1516
Set,
1617
Tuple,
1718
TypeVar,
@@ -1261,7 +1262,9 @@ def _maybe_to_dataarray(self, obj=None):
12611262
return obj
12621263

12631264
def rename_like(
1264-
self, other: Union[DataArray, Dataset]
1265+
self,
1266+
other: Union[DataArray, Dataset],
1267+
skip: Optional[Union[str, Iterable[str]]] = None,
12651268
) -> Union[DataArray, Dataset]:
12661269
"""
12671270
Renames variables in object to match names of like-variables in ``other``.
@@ -1277,20 +1280,30 @@ def rename_like(
12771280
----------
12781281
other : DataArray, Dataset
12791282
Variables will be renamed to match variable names in this xarray object
1283+
skip: str, Iterable[str], optional
1284+
Limit the renaming excluding
1285+
("axes", "cell_measures", "coordinates", "standard_names")
1286+
or a subset thereof.
12801287
12811288
Returns
12821289
-------
12831290
DataArray or Dataset with renamed variables
12841291
"""
1292+
skip = [skip] if isinstance(skip, str) else skip or []
1293+
12851294
ourkeys = self.keys()
12861295
theirkeys = other.cf.keys()
12871296

12881297
good_keys = ourkeys & theirkeys
12891298
keydict = {}
12901299
for key in good_keys:
1291-
ours = _get_all(self._obj, key)
1292-
theirs = _get_all(other, key)
1293-
keydict[key] = dict(ours=ours, theirs=theirs)
1300+
ours = set(_get_all(self._obj, key))
1301+
theirs = set(_get_all(other, key))
1302+
for attr in skip:
1303+
ours -= set(getattr(self, attr).get(key, []))
1304+
theirs -= set(getattr(other.cf, attr).get(key, []))
1305+
if ours and theirs:
1306+
keydict[key] = dict(ours=list(ours), theirs=list(theirs))
12941307

12951308
conflicts = {}
12961309
for k0, v0 in keydict.items():
@@ -1299,7 +1312,7 @@ def rename_like(
12991312
continue
13001313
for v1 in keydict.values():
13011314
# Conflicts have same ours but different theirs or vice versa
1302-
if sum([v0["ours"] == v1["ours"], v0["theirs"] == v1["theirs"]]) == 1:
1315+
if (v0["ours"] == v1["ours"]) != (v0["theirs"] == v1["theirs"]):
13031316
conflicts[k0] = v0
13041317
break
13051318
if conflicts:

cf_xarray/tests/test_accessor.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,8 +250,14 @@ def test_rename_like():
250250
assert "TEMP" in renamed
251251

252252
# skip conflicting variables
253+
da = popds.cf["TEMP"]
253254
with pytest.warns(UserWarning, match="Conflicting variables skipped:.*"):
254-
popds.cf.rename_like(airds)
255+
expected = {"longitude": ["TLONG"], "latitude": ["TLAT"]}
256+
actual = da.cf.rename_like(airds).cf.coordinates
257+
assert expected == actual
258+
expected = {"longitude": ["lon"], "latitude": ["lat"]}
259+
actual = da.cf.rename_like(airds, skip="axes").cf.coordinates
260+
assert expected == actual
255261

256262

257263
@pytest.mark.parametrize("obj", objects)

doc/examples/introduction.ipynb

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -605,10 +605,10 @@
605605
"cell_type": "markdown",
606606
"metadata": {},
607607
"source": [
608-
"If we drop the `X` and `Y` axes, a one-to-one mapping is possible. In this\n",
609-
"example, `TLONG` and `TLAT` are renamed to `lon` and `lat` i.e. their\n",
610-
"counterparts in `ds`. Note the the `coordinates` attribute is appropriately\n",
611-
"changed.\n"
608+
"If we exclude all axes (variables with `axis` attribute), a one-to-one mapping\n",
609+
"is possible. In this example, `TLONG` and `TLAT` are renamed to `lon` and `lat`\n",
610+
"i.e. their counterparts in `ds`. Note the the `coordinates` attribute is\n",
611+
"appropriately changed.\n"
612612
]
613613
},
614614
{
@@ -622,8 +622,7 @@
622622
},
623623
"outputs": [],
624624
"source": [
625-
"da = da.cf.drop_vars([\"X\", \"Y\"])\n",
626-
"da.cf.rename_like(ds)"
625+
"da.cf.rename_like(ds, skip=\"axes\")"
627626
]
628627
},
629628
{

0 commit comments

Comments
 (0)