代码之家  ›  专栏  ›  技术社区  ›  Exp HP

为什么分配'xr。对数据集变量更改不相关的坐标?

  •  0
  • Exp HP  · 技术社区  · 8 年前

    当我分配 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
    

    为什么 unrelated 使用后丢失维度 xr。ones\u喜欢 ?

    1 回复  |  直到 8 年前
        1
  •  1
  •   shoyer    8 年前

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

    这似乎是由于 xr.ones_like(ds['source'].isel(c=0)) 坐标值不同 'unrelated' ,它(错误地)覆盖了现有协调。因此,作为一种解决方法,您可以在将其指定给之前删除此额外坐标 ds['dest-2'] ,例如

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

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