假设我有两个数据集,每个数据集都包含一个不同的感兴趣变量,并且具有不完整(但不冲突)的索引:
In [1]: import xarray as xr, numpy as np
In [2]: ages = xr.Dataset(
{'ages': (['kid_ids'], np.random.rand((3))*20)},
coords={'kid_names':(['kid_ids'], ['carl','kathy','gail']), 'kid_ids': [10,14,16]})
In [3]: heights = xr.Dataset(
{'heights': (['kid_ids'], np.random.rand((3))*160)},
coords={'kid_names':(['kid_ids'], ['carl','keith','gail']), 'kid_ids': [10,13,16]})
这将创建两个数据集,看起来它们应该很好地合并:
In [4]: ages
Out[4]:
<xarray.Dataset>
Dimensions: (kid_ids: 3)
Coordinates:
* kid_ids (kid_ids) int32 10 14 16
kid_names (kid_ids) <U5 'carl' 'kathy' 'gail'
Data variables:
ages (kid_ids) float64 13.28 1.955 4.327
In [5]: heights
Out[5]:
<xarray.Dataset>
Dimensions: (kid_ids: 3)
Coordinates:
* kid_ids (kid_ids) int32 10 13 16
kid_names (kid_ids) <U5 'carl' 'keith' 'gail'
Data variables:
heights (kid_ids) float64 115.0 38.2 31.65
但是它们不行 - 尝试 ages.merge(heights)
会导致一个 ValueError
:
ValueError: conflicting value for variable kid_names:
first value: <xarray.Variable (kid_ids: 4)>
array(['carl', nan, 'kathy', 'gail'], dtype=object)
second value: <xarray.Variable (kid_ids: 4)>
array(['carl', 'keith', nan, 'gail'], dtype=object)
删除协调器
kid_names
即可解决问题:In [7]: ages.reset_coords('kid_names', drop=True).merge(
heights.reset_coords('kid_names', drop=True))
Out[7]:
<xarray.Dataset>
Dimensions: (kid_ids: 4)
Coordinates:
* kid_ids (kid_ids) int64 10 13 14 16
Data variables:
ages (kid_ids) float64 0.4473 nan 6.45 6.787
heights (kid_ids) float64 78.42 78.43 nan 113.4
看起来坐标的处理方式像是使用了 DataArrays
,即任何非相同的值都会引发错误。但它们不应该更像基本坐标,例如扩展为两个索引的超集吗?或者我应该执行另一个操作吗?
我正在使用 python 3.5,xarray 0.7.2 和 numpy 1.10.4。