xarray.Dataset.copy (original) (raw)

Dataset.copy(deep=False, data=None)[source]#

Returns a copy of this dataset.

If deep=True, a deep copy is made of each of the component variables. Otherwise, a shallow copy of each of the component variable is made, so that the underlying memory region of the new dataset is the same as in the original dataset.

Use data to create a new object with the same structure as original but entirely new data.

Parameters:

Returns:

object (Dataset) – New object with dimensions, attributes, coordinates, name, encoding, and optionally data copied from original.

Examples

Shallow copy versus deep copy

da = xr.DataArray(np.random.randn(2, 3)) ds = xr.Dataset( ... {"foo": da, "bar": ("x", [-1, 2])}, ... coords={"x": ["one", "two"]}, ... ) ds.copy() <xarray.Dataset> Size: 88B Dimensions: (dim_0: 2, dim_1: 3, x: 2) Coordinates:

ds_0 = ds.copy(deep=False) ds_0["foo"][0, 0] = 7 ds_0 <xarray.Dataset> Size: 88B Dimensions: (dim_0: 2, dim_1: 3, x: 2) Coordinates:

ds <xarray.Dataset> Size: 88B Dimensions: (dim_0: 2, dim_1: 3, x: 2) Coordinates:

Changing the data using the data argument maintains the structure of the original object, but with the new data. Original object is unaffected.

ds.copy(data={"foo": np.arange(6).reshape(2, 3), "bar": ["a", "b"]}) <xarray.Dataset> Size: 80B Dimensions: (dim_0: 2, dim_1: 3, x: 2) Coordinates:

ds <xarray.Dataset> Size: 88B Dimensions: (dim_0: 2, dim_1: 3, x: 2) Coordinates: