You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于滑动窗口而非固定窗口计算xarray xclim气候指数?

基于滑动窗口计算xclim气候指数

xclim的气候指数默认基于固定时间重采样频率(如每月初freq='MS')计算,若要实现逐月滑动窗口的指数计算,可以通过xarray的滑动窗口工具结合xclim指数函数来完成。

原固定窗口计算示例

以下是基于月度固定窗口计算热浪指数的代码:

import numpy as np
import pandas as pd
import xarray as xr
import xclim.indices as xci

# 生成模拟温度数据
T = xr.DataArray(np.random.normal(loc=300,scale=2,size=365), dims="time", 
                      coords={"time": pd.date_range(start='2000',periods=365, freq='d')})

ds=T.to_dataset(name='T')
ds['T'].attrs['units'] = 'K'

# 基于固定月度窗口计算热浪指数
hwi = xci.heat_wave_index(ds.T, freq='MS')

滑动窗口计算实现思路

xclim的指数函数本身不直接支持滑动窗口参数,因此我们可以通过以下步骤实现:

  • 用xarray的rolling创建滑动窗口对象,将每个窗口的数据集展开为新维度
  • 对每个滑动窗口单独调用xclim指数函数,批量完成计算

滑动窗口热浪指数计算代码

import numpy as np
import pandas as pd
import xarray as xr
import xclim.indices as xci

# 生成模拟温度数据
T = xr.DataArray(
    np.random.normal(loc=300, scale=2, size=365),
    dims="time",
    coords={"time": pd.date_range(start='2000', periods=365, freq='d')}
)
ds = T.to_dataset(name='T')
ds['T'].attrs['units'] = 'K'

# 设置滑动窗口参数:窗口大小30天,步长1天(逐月滑动)
window_size = 30
# 构建滑动窗口数据集,新增window_time维度存储每个窗口的时间序列
rolling_ds = ds.rolling(time=window_size, center=False).construct(window_dim="window_time")

# 定义每个窗口的指数计算函数
def calc_hwi(window_data):
    return xci.heat_wave_index(window_data.T)

# 对所有滑动窗口批量计算热浪指数
hwi_sliding = rolling_ds.groupby("time").map(calc_hwi)

代码说明

  • rolling(time=30, center=False):设置窗口大小为30天,窗口以当前时间为结束点;若需要窗口居中,可将center设为True
  • construct(window_dim="window_time"):将每个滑动窗口的时间序列展开为新维度,方便后续逐窗口计算
  • groupby("time").map(calc_hwi):遍历每个滑动窗口,应用热浪指数计算逻辑

内容的提问来源于stack exchange,提问作者Janet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:05:30