Python中xarray Dataset无法添加二维维度的问题求助
xarray设置二维数据变量维度失败的解决方案
问题背景
我想要给变量设置的维度列表是:['Time', 'Pressure', 'Temperature', 'Electrical conductivity', 'Salinity', 'Chlorophyll concentration'],但尝试为数据变量设置二维维度时触发报错。
失败的代码及报错
执行以下代码:
ds = xr.Dataset( coords = coords, data_vars = {"hehe" : (('Time', 'Pres'), col_names_values2['c731'])}, attrs = global_attributes )
触发报错:
ValueError: Could not convert tuple of form (dims, data[, attrs, encoding]): (('Time', 'Pres'), [55, 22]) to Variable.
单一维度设置正常的情况
仅设置单一维度时运行正常,得到结果:
<xarray.Dataset> Dimensions: (Time: 55, Pres: 55, Temp: 55, Cond: 55, Sal: 55, CHL: 55) Coordinates: * Time (Time) int32 55 * Pres (Pres) float64 55 * Temp (Temp) float64 55 * Cond (Cond) float64 55 * Sal (Sal) float64 55 * CHL (CHL) float64 55 Data variables: hehe (Time) float64 55
参考官方示例的成功代码
参考xarray官方文档示例编写的代码能成功运行:
ds = xr.Dataset( coords = coords, data_vars = {"foo": (("x", "y"), np.random.rand(4, 5))}, attrs = global_attributes )
运行结果:
<xarray.Dataset> Dimensions: (x: 4, y: 5, Time: 55, Pres: 55, Temp: 55, Cond: 55, Sal: 55, chl: 55) Coordinates: * Time (Time) 55 * Pres (Pres) 55 * Temp (Temp) 55 * Cond (Cond) 55 * Sal (Sal) 55 * CHL (CHL) 55 Dimensions without coordinates: x, y Data variables: foo (x, y) float64 55
解决方案
问题核心是数据形状与指定维度的长度不匹配:
- 你指定的二维维度
('Time', 'Pres'),两个维度长度都是55,对应的数据必须是(55, 55)的二维数组。 - 但你传入的
col_names_values2['c731']是[55, 22],这是长度为2的一维数组,和二维维度要求的形状完全不符,因此触发报错。 - 官方示例中
np.random.rand(4,5)的形状(4,5)正好和维度('x','y')的长度4、5对应,所以能正常运行。
具体解决步骤:
- 检查
col_names_values2['c731']的数据形状,确保其维度数与指定维度数量一致,且每个维度长度和对应坐标的长度匹配。 - 如果数据确实是二维的,将其转换为
(Time长度, Pres长度)的二维数组(比如用numpy.reshape);如果数据是一维的,要么调整为单一维度,要么确认是否需要通过广播等方式扩充维度。
示例代码(假设数据需要转为55×55的二维数组):
import numpy as np # 根据实际数据调整reshape的参数 data_2d = np.reshape(col_names_values2['c731'], (55, 55)) ds = xr.Dataset( coords = coords, data_vars = {"hehe" : (('Time', 'Pres'), data_2d)}, attrs = global_attributes )
内容的提问来源于stack exchange,提问作者user21620824
相关产品推荐
相关产品推荐

