Skip to content

Commit f63ad3b

Browse files
committed
Add accessor method cf.assign().
1 parent 24dd81b commit f63ad3b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

cf_xarray/accessor.py

+48
Original file line numberDiff line numberDiff line change
@@ -2633,6 +2633,54 @@ def grid_mapping_names(self) -> dict[str, list[str]]:
26332633
results[v].append(k)
26342634
return results
26352635

2636+
def assign(self, **standard_variables: Any) -> Dataset:
2637+
"""Assign new variables by standard_name.
2638+
2639+
Parameters
2640+
----------
2641+
standard_variables : mapping
2642+
A mapping from netCDF Climate and Forecast compliant standard names
2643+
(http://cfconventions.org/standard-names.html), to the new values.
2644+
The new values are passed to ``:meth:Dataset.assign``.
2645+
2646+
Returns
2647+
-------
2648+
dataset : Dataset
2649+
A new dataset with the new variables added, replacing any existing
2650+
variable with the same standard name. New variables are labelled
2651+
according to their input (short) names, or standard names if short
2652+
names are missing, with added trailing underscores in the event of
2653+
duplicates.
2654+
2655+
See Also
2656+
--------
2657+
DataSet.assign
2658+
"""
2659+
2660+
# initalize dictionary mapping short names to the new variables
2661+
variables = {}
2662+
2663+
# for each standard name and value pair
2664+
for standard_name, values in standard_variables.items():
2665+
2666+
# default to using existing short name or standard name
2667+
name = getattr(values, "name", standard_name)
2668+
2669+
# add trailing underscores until we find a free slot
2670+
while name in self._obj.data_vars or name in variables:
2671+
emit_user_level_warning(
2672+
f"found existing variable {name}, using {name}_ instead",
2673+
UserWarning)
2674+
name += '_'
2675+
2676+
# map name to values (without coords, see #513, xarray#6447)
2677+
values = xr.as_variable(values)
2678+
values.attrs.update(standard_name=standard_name)
2679+
variables[name] = values
2680+
2681+
# assign new variables and return a new dataset
2682+
return self._obj.assign(variables)
2683+
26362684
def decode_vertical_coords(self, *, outnames=None, prefix=None):
26372685
"""
26382686
Decode parameterized vertical coordinates in place.

0 commit comments

Comments
 (0)