Closed
Description
I don't know if this is intentional, I thought that arr.copy(deep=True)
or deepcopy(arr)
would give me completely independent copies of a DateArray, but this seems not be the case?
>>> import xarray as xr
>>> xarr1 = xr.DataArray([1,2], coords=dict(x=[0,1]), dims=('x',))
>>> xarr1.x.data[0]
0
>>> xarr2 = xarr1.copy(deep=True) #xarr2 = deepcopy(xarr1) -> leads to same result
>>> xarr2.x.data[0] = -1
>>> xarr1.x.data[0]
-1
How can I create completely independent copies of a DateArray? I wrote a function for this, but don't know if this really always does what I expect and if there is a more elegant way?
def deepcopy_xarr(xarr):
"""
Deepcopy for xarray that makes sure coords and attrs
are properly deepcopied.
With normal copy method from xarray, when i mutated
xarr.coords[coord].data it would also mutate in the copy
and vice versa.
Parameters
----------
xarr: DateArray
Returns
-------
xcopy: DateArray
Deep copy of xarr
"""
xcopy = xarr.copy(deep=True)
for dim in xcopy.coords:
xcopy.coords[dim].data = np.copy(xcopy.coords[dim].data)
xcopy.attrs = deepcopy(xcopy.attrs)
for attr in xcopy.attrs:
xcopy.attrs[attr] = deepcopy(xcopy.attrs[attr])
return xcopy