Skip to content

Commit 772f7e0

Browse files
crusaderkyshoyer
authored andcommitted
Dataset.copy() to preserve encoding (#1590)
* Dataset.copy() to preserve encoding * Fix sphinx hook * Add unit test
1 parent 5bd4015 commit 772f7e0

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

doc/whats-new.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,10 @@ Bug fixes
209209
when objects other than ``Dataset`` are provided (:issue:`1555`).
210210
By `Joe Hamman <https://github.com/jhamman>`_.
211211

212+
- :py:func:`xarray.Dataset.copy` would not preserve the encoding property
213+
(:issue:`1586`).
214+
By `Guido Imperiale <https://github.com/crusaderky>`_.
215+
212216
- :py:func:`xarray.concat` would eagerly load dask variables into memory if
213217
the first argument was a numpy variable (:issue:`1588`).
214218
By `Guido Imperiale <https://github.com/crusaderky>`_.

xarray/core/dataset.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,8 @@ def copy(self, deep=False):
634634
for k, v in iteritems(self._variables))
635635
# skip __init__ to avoid costly validation
636636
return self._construct_direct(variables, self._coord_names.copy(),
637-
self._dims.copy(), self._attrs_copy())
637+
self._dims.copy(), self._attrs_copy(),
638+
encoding=self.encoding)
638639

639640
def _subset_with_all_valid_coords(self, variables, coord_names, attrs):
640641
needed_dims = set()

xarray/tests/test_dataset.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def create_test_data(seed=None):
5050
obj[v] = (dims, data, {'foo': 'variable'})
5151
obj.coords['numbers'] = ('dim3', np.array([0, 1, 2, 0, 0, 1, 1, 2, 2, 3],
5252
dtype='int64'))
53+
obj.encoding = {'foo': 'bar'}
5354
assert all(obj.data.flags.writeable for obj in obj.values())
5455
return obj
5556

@@ -1434,6 +1435,7 @@ def test_copy(self):
14341435

14351436
for copied in [data.copy(deep=False), copy(data)]:
14361437
self.assertDatasetIdentical(data, copied)
1438+
self.assertEqual(data.encoding, copied.encoding)
14371439
# Note: IndexVariable objects with string dtype are always
14381440
# copied because of xarray.core.util.safe_cast_to_index.
14391441
# Limiting the test to data variables.

0 commit comments

Comments
 (0)