@@ -2633,6 +2633,54 @@ def grid_mapping_names(self) -> dict[str, list[str]]:
2633
2633
results [v ].append (k )
2634
2634
return results
2635
2635
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
+
2636
2684
def decode_vertical_coords (self , * , outnames = None , prefix = None ):
2637
2685
"""
2638
2686
Decode parameterized vertical coordinates in place.
0 commit comments