假设我有两个数据集,每个数据集都包含不同的感兴趣变量和不完整(但不冲突)的索引:
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