@@ -77,9 +77,11 @@ def merge_mappings(first, *mappings):
77
77
return result
78
78
79
79
80
- def units_to_str_or_none (mapping ):
80
+ def units_to_str_or_none (mapping , unit_format ):
81
+ formatter = str if not unit_format else lambda v : unit_format .format (v )
82
+
81
83
return {
82
- key : str (value ) if isinstance (value , Unit ) else value
84
+ key : formatter (value ) if isinstance (value , Unit ) else value
83
85
for key , value in mapping .items ()
84
86
}
85
87
@@ -241,7 +243,7 @@ def quantify(self, units=None, unit_registry=None, **unit_kwargs):
241
243
conversion .attach_units , units
242
244
)
243
245
244
- def dequantify (self ):
246
+ def dequantify (self , format = None ):
245
247
"""
246
248
Removes units from the DataArray and its coordinates.
247
249
@@ -253,15 +255,19 @@ def dequantify(self):
253
255
dequantified : DataArray
254
256
DataArray whose array data is unitless, and of the type
255
257
that was previously wrapped by `pint.Quantity`.
258
+ format : str, optional
259
+ The format used for the string representations.
256
260
"""
257
-
258
261
units = conversion .extract_unit_attributes (self .da )
259
262
units .update (conversion .extract_units (self .da ))
260
263
264
+ unit_format = f"{{:{ format } }}" if isinstance (format , str ) else format
265
+
266
+ units = units_to_str_or_none (units , unit_format )
261
267
return (
262
268
self .da .pipe (conversion .strip_units )
263
269
.pipe (conversion .strip_unit_attributes )
264
- .pipe (conversion .attach_unit_attributes , units_to_str_or_none ( units ) )
270
+ .pipe (conversion .attach_unit_attributes , units )
265
271
)
266
272
267
273
@property
@@ -504,7 +510,7 @@ def quantify(self, units=None, unit_registry=None, **unit_kwargs):
504
510
conversion .attach_units , units
505
511
)
506
512
507
- def dequantify (self ):
513
+ def dequantify (self , format = None ):
508
514
"""
509
515
Removes units from the Dataset and its coordinates.
510
516
@@ -516,14 +522,19 @@ def dequantify(self):
516
522
dequantified : Dataset
517
523
Dataset whose data variables are unitless, and of the type
518
524
that was previously wrapped by ``pint.Quantity``.
525
+ format : str, optional
526
+ The format used for the string representations.
519
527
"""
520
528
units = conversion .extract_unit_attributes (self .ds )
521
529
units .update (conversion .extract_units (self .ds ))
522
530
531
+ unit_format = f"{{:{ format } }}" if isinstance (format , str ) else format
532
+
533
+ units = units_to_str_or_none (units , unit_format )
523
534
return (
524
535
self .ds .pipe (conversion .strip_units )
525
536
.pipe (conversion .strip_unit_attributes )
526
- .pipe (conversion .attach_unit_attributes , units_to_str_or_none ( units ) )
537
+ .pipe (conversion .attach_unit_attributes , units )
527
538
)
528
539
529
540
def to (self , units = None , ** unit_kwargs ):
0 commit comments