xarray (教程)第四章 插值的使用

Interpolating data

Xarray提供了灵活的插值例程,与我们的索引有相似的接口。
interp需要安装scipy。

Scalar and 1-dimensional interpolation

对数据数组进行插值的工作方式很像对数据数组进行标记索引,

da = xr.DataArray(
    np.sin(0.3 * np.arange(12).reshape(4, 3)),
    [("time", np.arange(4)), ("space", [0.1, 0.2, 0.3])],
)

# label lookup
da.sel(time=3)
"""Out[2]: 
<xarray.DataArray (space: 3)>
array([ 0.427,  0.141, -0.158])
Coordinates:
    time     int64 3
  * space    (space) float64 0.1 0.2 0.3"""

# interpolation
da.interp(time=2.5)
"""Out[3]: 
<xarray.DataArray (space: 3)>
array([0.701, 0.502, 0.259])
Coordinates:
  * space    (space) float64 0.1 0.2 0.3
    time     float64 2.5"""

与索引类似,interp()也接受类似数组的,它将插值结果作为数组给出。

# label lookup
da.sel(time=[2, 3])
"""Out[4]: 
<xarray.DataArray (time: 2, space: 3)>
array([[ 0.974,  0.863,  0.675],
       [ 0.427,  0.141, -0.158]])
Coordinates:
  * time     (time) int64 2 3
  * space    (space) float64 0.1 0.2 0.3
"""
# interpolation
da.interp(time=[2.5, 3.5])
"""Out[5]: 
<xarray.DataArray (time: 2, space: 3)>
array([[0.701, 0.502, 0.259],
       [  nan,   nan,   nan]])
Coordinates:
  * space    (space) float64 0.1 0.2 0.3
  * time     (time) float64 2.5 """
3.5

要使用numpy.datetime64坐标插值数据,可以传递一个字符串。

da_dt64 = xr.DataArray(
    [1, 3], [("time", pd.date_range("1/1/2000", "1/3/2000", periods=2))]
)

da_dt64.interp(time="2000-01-02")
"""Out[7]: 
<xarray.DataArray ()>
array(2.)
Coordinates:
    time     datetime64[ns] 2000-01-02"""

通过指定所需的时间段,可以将插值数据合并到原始数据阵列中。

da_dt64.interp(time=pd.date_range("1/1/2000", "1/3/2000", periods=3))
"""Out[8]: 
<xarray.DataArray (time: 3)>
array([1., 2., 3.])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03"""

也允许对CFTimeIndex索引的数据进行插值。
目前,我们的插值只适用于规则的网格。因此,与sel()类似,只有沿一个维度的1D坐标可以用作要插值的原始坐标。

Multi-dimensional Interpolation

和sel()一样,interp()接受多个坐标。在这种情况下,执行多维插值。

# label lookup
da.sel(time=2, space=0.1)
"""Out[9]: 
<xarray.DataArray ()>
array(0.974)
Coordinates:
    time     int64 2
    space    float64 0.1"""

# interpolation
da.interp(time=2.5, space=0.15)
"""Out[10]: 
<xarray.DataArray ()>
array(0.601)
Coordinates:
    time     float64 2.5
    space    float64 0.15"""

也接受类似数组的坐标:

# label lookup
da.sel(time=[2, 3], space=
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值