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

如何调整xarray DataArray的坐标显示顺序以匹配维度顺序?

解决Xarray转置后坐标显示顺序不匹配的问题

当你用transpose转置DataArray后,xarray默认会按坐标名称的字母顺序打印坐标,而非维度的实际顺序。要让坐标显示顺序和转置后的维度顺序一致,可以用set_coords方法显式指定坐标顺序:

import numpy as np
import xarray as xr

data = xr.DataArray(
    np.arange(24).reshape(2, 3, 4),
    dims=['x', 'y', 'z'],
    coords={
        'x': ['a', 'b'],
        'y': [10, 20, 30],
        'z': [100, 200, 300, 400]
    }
)

# 转置后指定坐标显示顺序为z、y、x
transposed_data = data.transpose('z', 'y', 'x').set_coords(['z', 'y', 'x'])

print(transposed_data)

此时打印的结果中,坐标会按z、y、x的顺序显示:

>>> print(transposed_data)
<xarray.DataArray (z: 4, y: 3, x: 2)>
array([[[ 0,  4],
        [ 8, 12],
        [16, 20]],

       [[ 1,  5],
        [ 9, 13],
        [17, 21]],

       [[ 2,  6],
        [10, 14],
        [18, 22]],

       [[ 3,  7],
        [11, 15],
        [19, 23]]])
Coordinates:
  * z        (z) int64 100 200 300 400
  * y        (y) int64 10 20 30
  * x        (x) <U1 'a' 'b'

原理是set_coords会重新定义DataArray中坐标的存储顺序,xarray打印时会遵循这个顺序来展示坐标,而不再使用默认的字母排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:52:16