Python 为什么将'xr.ones_like'赋值给数据集变量会改变不相关的坐标?

Python 为什么将'xr.ones_like'赋值给数据集变量会改变不相关的坐标?,python,python-xarray,Python,Python Xarray,当我将xr.ones_like的结果分配给数据集变量时,我会丢失分配给坐标的一些数据: import xarray as xr import numpy as np A, B, C = 2, 3, 4 ds = xr.Dataset() ds.coords['source'] = (['a', 'b', 'c'], np.random.random((A, B, C))) ds.coords['unrelated'] = (['a', 'c'], np.random.random((A, C

当我将xr.ones_like的结果分配给数据集变量时,我会丢失分配给坐标的一些数据:

import xarray as xr
import numpy as np

A, B, C = 2, 3, 4

ds = xr.Dataset()
ds.coords['source'] = (['a', 'b', 'c'], np.random.random((A, B, C)))
ds.coords['unrelated'] = (['a', 'c'], np.random.random((A, C)))

print('INITIAL:', ds['unrelated'], '\n')

# do 'ones_like' manually
ds['dest-1'] = (['a', 'b'], np.ones((A, B)))

print('AFTER dest-1:', ds['unrelated'], '\n')

ds['dest-2'] = xr.ones_like(ds['source'].isel(c=0))

print('AFTER dest-2:', ds['unrelated'], '\n')
输出:

INITIAL: <xarray.DataArray 'unrelated' (a: 2, c: 4)>
array([[0.185851, 0.962589, 0.772985, 0.570292],
       [0.905792, 0.865125, 0.412361, 0.666977]])
Coordinates:
    unrelated  (a, c) float64 0.1859 0.9626 0.773 0.5703 0.9058 0.8651 ...
Dimensions without coordinates: a, c

AFTER dest-1: <xarray.DataArray 'unrelated' (a: 2, c: 4)>
array([[0.185851, 0.962589, 0.772985, 0.570292],
       [0.905792, 0.865125, 0.412361, 0.666977]])
Coordinates:
    unrelated  (a, c) float64 0.1859 0.9626 0.773 0.5703 0.9058 0.8651 ...
Dimensions without coordinates: a, c

AFTER dest-2: <xarray.DataArray 'unrelated' (a: 2)>
array([0.185851, 0.905792])
Coordinates:
    unrelated  (a) float64 0.1859 0.9058
Dimensions without coordinates: a

为什么在使用xr.ones_like后会丢失维度?

简而言之,这种行为看起来像。如果没有某种明确的选择,分配变量肯定不应该修改现有坐标

这似乎是由xr.ones_likeds['source'].iselc=0对坐标“unrelated”具有不同的值造成的,该值错误地覆盖了现有坐标。因此,作为一种解决方法,您可以在将此额外坐标分配给ds['dest-2']之前删除它,例如,使用

ds['dest-2'] = xr.ones_like(ds['source'].isel(c=0)).drop('unrelated')

哦,谢天谢地!这是我基本上怀疑正在发生的事情,但我担心这是故意的=P
ds['dest-2'] = xr.ones_like(ds['source'].isel(c=0)).reset_coords(drop=True)