MCPcopy
hub / github.com/pydata/xarray / attach_units

Function attach_units

xarray/tests/test_units.py:186–227  ·  view source on GitHub ↗
(obj, units)

Source from the content-addressed store, hash-verified

184
185
186def attach_units(obj, units):
187 if not isinstance(obj, xr.DataArray | xr.Dataset | xr.Variable):
188 units = units.get("data", None) or units.get(None, None) or 1
189 return array_attach_units(obj, units)
190
191 if isinstance(obj, xr.Dataset):
192 data_vars = {
193 name: attach_units(value, units) for name, value in obj.data_vars.items()
194 }
195
196 coords = {
197 name: attach_units(value, units) for name, value in obj.coords.items()
198 }
199
200 new_obj = xr.Dataset(data_vars=data_vars, coords=coords, attrs=obj.attrs)
201 elif isinstance(obj, xr.DataArray):
202 # try the array name, "data" and None, then fall back to dimensionless
203 data_units = units.get(obj.name, None) or units.get(None, None) or 1
204
205 data = array_attach_units(obj.data, data_units)
206
207 coords = {
208 name: (
209 (value.dims, array_attach_units(value.data, units.get(name) or 1))
210 if name in units
211 else (value.dims, value.data)
212 )
213 for name, value in obj.coords.items()
214 }
215 dims = obj.dims
216 attrs = obj.attrs
217
218 new_obj = xr.DataArray( # type: ignore[assignment]
219 name=obj.name, data=data, coords=coords, attrs=attrs, dims=dims
220 )
221 else:
222 data_units = units.get("data", None) or units.get(None, None) or 1
223
224 data = array_attach_units(obj.data, data_units)
225 new_obj = obj.copy(data=data) # type: ignore[assignment]
226
227 return new_obj
228
229
230def convert_units(obj, to):

Callers 15

test_apply_ufunc_datasetFunction · 0.85
test_align_dataarrayFunction · 0.85
test_align_datasetFunction · 0.85
test_broadcast_dataarrayFunction · 0.85
test_broadcast_datasetFunction · 0.85
test_combine_by_coordsFunction · 0.85
test_combine_nestedFunction · 0.85
test_concat_dataarrayFunction · 0.85
test_concat_datasetFunction · 0.85
test_merge_dataarrayFunction · 0.85
test_merge_datasetFunction · 0.85

Calls 4

array_attach_unitsFunction · 0.85
itemsMethod · 0.80
getMethod · 0.45
copyMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…