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

如何更改xarray.Dataset的维度顺序且不改动其他内容?

实现方法

直接使用xarray内置的transpose方法即可完成维度顺序调整,该操作不会改动数据集内的数值、坐标映射关系等任何其他内容,仅调整维度的排列顺序。

对应操作代码如下:

import numpy as np
import xarray as xr

# 原数据集创建逻辑
x_example = np.random.rand(1488,)
y_example = np.random.rand(1331,)
time_example = np.random.rand(120,)
rainfall_example = np.random.rand(120, 1331, 1488)

rainfall_dataset = xr.Dataset(
    data_vars=dict(
        rainfall_depth=(['time', 'y', 'x'], rainfall_example),
    ),
    coords=dict(
        time=(['time'], time_example),
        x=(['x'], x_example),
        y=(['y'], y_example)
    )
)

# 核心调整逻辑:传入目标维度顺序即可
rainfall_dataset = rainfall_dataset.transpose('time', 'x', 'y')

调整完成后执行print(rainfall_dataset.dims),即可得到目标输出:

Frozen({'time': 120, 'x': 1488, 'y': 1331})

补充说明:

  • 该方法会同步调整数据集内所有数据变量的维度顺序,不会出现维度错位、数值错乱问题
  • 如果调用transpose()时不传入任何参数,会默认将现有维度倒序排列
  • 若需要在原数据集对象上直接修改而不返回新对象,可以添加inplace=True参数(xarray 0.15及以上版本支持),写法为rainfall_dataset.transpose('time', 'x', 'y', inplace=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 12:54:33