Skip to content

Commit a2b1712

Browse files
authored
fix decode for scale/ offset list (pydata#4802)
* fix decode for scale/ offset list * typo
1 parent 84df75d commit a2b1712

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

doc/whats-new.rst

+2
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,8 @@ Bug fixes
7575
- Add ``missing_dims`` parameter to transpose (:issue:`4647`, :pull:`4767`). By `Daniel Mesejo <https://github.com/mesejo>`_.
7676
- Resolve intervals before appending other metadata to labels when plotting (:issue:`4322`, :pull:`4794`).
7777
By `Justus Magin <https://github.com/keewis>`_.
78+
- Fix regression when decoding a variable with a ``scale_factor`` and ``add_offset`` given
79+
as a list of length one (:issue:`4631`) by `Mathias Hauser <https://github.com/mathause>`_.
7880
- Expand user directory paths (e.g. ``~/``) in :py:func:`open_mfdataset` and
7981
:py:meth:`Dataset.to_zarr` (:issue:`4783`, :pull:`4795`).
8082
By `Julien Seguinot <https://github.com/juseg>`_.

xarray/coding/variables.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -270,9 +270,9 @@ def decode(self, variable, name=None):
270270
add_offset = pop_to(attrs, encoding, "add_offset", name=name)
271271
dtype = _choose_float_dtype(data.dtype, "add_offset" in attrs)
272272
if np.ndim(scale_factor) > 0:
273-
scale_factor = scale_factor.item()
273+
scale_factor = np.asarray(scale_factor).item()
274274
if np.ndim(add_offset) > 0:
275-
add_offset = add_offset.item()
275+
add_offset = np.asarray(add_offset).item()
276276
transform = partial(
277277
_scale_offset_decoding,
278278
scale_factor=scale_factor,

xarray/tests/test_coding.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from xarray.coding import variables
99
from xarray.conventions import decode_cf_variable, encode_cf_variable
1010

11-
from . import assert_equal, assert_identical, requires_dask
11+
from . import assert_allclose, assert_equal, assert_identical, requires_dask
1212

1313
with suppress(ImportError):
1414
import dask.array as da
@@ -105,3 +105,15 @@ def test_scaling_converts_to_float32(dtype):
105105
roundtripped = coder.decode(encoded)
106106
assert_identical(original, roundtripped)
107107
assert roundtripped.dtype == np.float32
108+
109+
110+
@pytest.mark.parametrize("scale_factor", (10, [10]))
111+
@pytest.mark.parametrize("add_offset", (0.1, [0.1]))
112+
def test_scaling_offset_as_list(scale_factor, add_offset):
113+
# test for #4631
114+
encoding = dict(scale_factor=scale_factor, add_offset=add_offset)
115+
original = xr.Variable(("x",), np.arange(10.0), encoding=encoding)
116+
coder = variables.CFScaleOffsetCoder()
117+
encoded = coder.encode(original)
118+
roundtripped = coder.decode(encoded)
119+
assert_allclose(original, roundtripped)

0 commit comments

Comments
 (0)