从 xarray 数据集创建 NetCDF 时纬度经度错误

Wrong latitude longitude when creating NetCDF from xarray dataset

我想用 xarray 创建一个 NetCDF 文件并尝试理解 'Creating a Dataset' here.

上的文档

这是示例中的代码(将 ds 保存到 NetCDF):

import xarray as xr
import numpy as np
import pandas as pd

temp = 15 + 8 * np.random.randn(2, 2, 3)
precip = 10 * np.random.rand(2, 2, 3)
lon = [[-99.83, -99.32], [-99.79, -99.23]]
lat = [[42.25, 42.21], [42.63, 42.59]]

ds = xr.Dataset({'temperature': (['x', 'y', 'time'],  temp),
                 'precipitation': (['x', 'y', 'time'], precip)},
                coords={'lon': (['x', 'y'], lon),
                        'lat': (['x', 'y'], lat), 
                        'time': pd.date_range('2014-09-06', periods=3),
                        'reference_time': pd.Timestamp('2014-09-05')})

ds.to_netcdf('C:\Temp\test.nc')

从上面的示例中,我希望得到一个具有三个维度(x、y、时间)的两个变量(温度、降水)的 NetCDF。我希望尺寸大小在 x 方向上为 2,在 y 方向上为 2,在时间方向上为 3。根据@Bart 的测试(评论),NetCDF 就是这种情况。 因此,当在 QGIS 3.4 (EPSG 4326) 中打开 NetCDF 'temp' 或 'precip' 变量时,我希望 NetCDF 数据是:

相反,数据是:

请查找 NetCDF 的可视化 here。红色方块标记了温度变量蓝色阴影的六个单元格,左上角点 (0/0) 的 lat/lon 和两个 'bands'

因此,xarray NetCDF 数据格式似乎与 QGIS 对该格式的解释不同。 有人可以编辑示例,以便它在 QGIS 的 'correct' 位置生成 2x2 网格,或者提供/指向一个简单示例以从 xarray 数据集创建正确地理参考的 NetCDF 吗?

我必须交换维度的顺序,并且我必须摆脱嵌套的经纬度列表才能正常工作。将 xarray 示例修改为此处的代码有效:

import xarray as xr
import numpy as np
import pandas as pd

temp = 15 + 8 * np.random.randn(3, 3, 2)  # time, y, x
precip = 10 * np.random.rand(3, 3, 2)  # time, y, x
lat = [100, 101, 102]
lon = [10, 11]

ds = xr.Dataset({'temperature': (['time', 'y', 'x'],  temp),
                 'precipitation': (['time', 'y', 'x'], precip)},
                coords={'x': (['x'], lon),
                        'y': (['y'], lat),
                        'time': pd.date_range('2014-09-06', periods=3)})

ds.to_netcdf('C:\Temp\test_xarray.nc')

请注意,我根据问题的要求将“2x2 网格”更改为“2x3 网格”,以确保 x-y 在创建 NetCDF 时的顺序很重要。