如何将Xarray DataArray的值作为维度添加至另一个DataArray并替换time维度?
用xarray重构数据并执行polyfit回归分析
需求背景
现有两个带x、y、time维度的DataArray(temperature和size),需要将time维度替换为temperature的唯一值(或分箱后的值),构建新的x、y、temperature维度数组,最终通过polyfit计算每个x/y组合下temperature与size的一阶回归系数。
解决方案
方法1:基于temperature唯一值重构数据
由于同一x/y下可能存在重复的temperature值,需先分组聚合再调整维度:
import xarray as xr import numpy as np # 生成示例数据 temperature = xr.DataArray( np.random.rand(5,5,30), coords=dict(x=range(5), y=range(5), time=range(30)), dims=('x','y','time') ) size = xr.DataArray( np.random.rand(5,5,30), coords=dict(x=range(5), y=range(5), time=range(30)), dims=('x','y','time') ) # 合并为Dataset统一处理 ds = xr.Dataset({'temperature': temperature, 'size': size}) # 按x、y、temperature分组,聚合size(此处用均值,可替换为median/sum等) ds_grouped = ds.groupby(['x', 'y', 'temperature']).mean() # 展开temperature为独立维度,得到目标数组 new_array = ds_grouped['size'].unstack(['temperature']) # 执行一阶多项式回归 fit_results = new_array.polyfit(dim='temperature', deg=1)
方法2:分箱处理(适用于temperature唯一值过多的场景)
通过分箱减少维度基数,再进行重构:
# 定义温度分箱区间(示例:分成10个等距区间) temp_bins = np.linspace(temperature.min(), temperature.max(), 11) # 按x、y和温度分箱分组,聚合size ds_binned = ds.groupby_bins('temperature', bins=temp_bins).mean() # 展开分箱维度为独立维度 new_array_binned = ds_binned['size'].unstack(['temperature_bins']) # 执行回归分析 fit_results_binned = new_array_binned.polyfit(dim='temperature_bins', deg=1)
关键说明
- 原尝试的
expand_dims无法满足需求,因为它只是新增维度而非替换/重组现有维度的数据结构,而groupby/groupby_bins才是实现“按temperature值重新组织size数据”的正确方式。 - 分组后的聚合步骤是必须的:xarray要求坐标值唯一,同一
x/y/temperature组合下的多个size值需通过聚合(均值/中位数等)合并为单一值。
内容的提问来源于stack exchange,提问作者Jesse Anderson
相关产品推荐
相关产品推荐

