xarray-contrib/cf-xarray

Return custom name for DataArray

Opened this issue · 2 comments

This came up in #234 and I want to capture the idea here:

I'd like to be able to not just ask for the "ssh" variable for example, but ask which type of variable I have. So in addition to:

ds.cf["ssh"]

returning the "ssh"-matching variable, I would like to be able to, for a DataArray da:

da.cf._get_custom_type()

to return "ssh", or somehow do the inverse search, returning the custom names that match the DataArray.

@dcherian is there an analogous function in the accessor code that would make sense to copy for this?

This may be useful:

newmap = {}
inverted = invert_mappings(
accessor.axes,
accessor.coordinates,
accessor.cell_measures,
accessor.standard_names,
)
unused_keys = set(attribute.keys()) - set(inverted)
for key, value in attribute.items():
for name in inverted[key]:
if name in newmap:
raise AttributeError(
f"cf_xarray can't wrap attribute {attr!r} because there are multiple values for {name!r}. "
f"There is no unique mapping from {name!r} to a value in {attr!r}."
)
newmap.update(dict.fromkeys(inverted[key], value))
newmap.update({key: attribute[key] for key in unused_keys})
skip = {"data_vars": ["coords"], "coords": None}
if attr in ["coords", "data_vars"]:
for key in newmap:
newmap[key] = _getitem(accessor, key, skip=skip[attr])
return newmap

It rewrites things like .chunks and .sizes when a one-to-one mapping is possible