当索引名称具有多个维度时,如何使用 xarray 导入 netCDF4 文件?

How to import netCDF4 file with xarray when index names have multiple dimensions?

当我尝试使用 xarray 导入 netCDF4 文件时出现以下错误:

MissingDimensionsError:'name' 具有多个 1 维并且与其维度之一同名('time'、'name')。 xarray 不允许此类变量,因为它们与用于标记维度的坐标冲突。

但是,我可以使用netCDF4 python 库成功导入这些数据,并从中获取我需要的数据。问题是这种方法很慢,所以我一直在寻找更快的东西,想试试 xarray。 Here is an example file, 以及给出问题错误的代码。

from netCDF4 import Dataset
#import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np         
#import seaborn as sns
from tkinter import Tk

from tkinter.filedialog import askdirectory
import os
import xarray as xr

#use this function to get a directory name where the files are
def get_dat():
    root = Tk()
    root.withdraw()
    root.focus_force()
    root.attributes("-topmost", True)      #makes the dialog appear on top
    filename = askdirectory()      # Open single file
    root.destroy()
    root.quit()
    return filename

directory=get_dat()

#loop through files in directory and read the netCDF4 files
for filename in os.listdir(directory):     #loop through files in user's dir
    if filename.endswith(".nc"):     #all my files are .nc not .nc4
        runstart=pd.datetime.now()
        #I get the error right here
        rootgrp3 = xr.open_dataset(directory+'/'+filename)
        #more stuff happens here with the data, but this stuff works

该问题目前仍然有效。当坐标具有多个维度并且与其中一个维度的名称相同时,就会出现问题。

例如,GOTM model 发布的输出文件 result.nc 对于坐标 zzi 有这个问题:

dimensions:
    time = UNLIMITED ; // (4018 currently)
    lon = 1 ;
    lat = 1 ;
    z = 218 ;
    zi = 219 ;
variables:
    ... 
    float z(time, z, lat, lon) ;
    float zi(time, zi, lat, lon) ;

有人提议 here 对 xr.open_dataset() 实施 'rename_var' kwarg 作为变通方法,但据我所知尚未实施。

我使用的 快速解决方法 是在需要时从 python 调用 nco-ncrename。

就我而言:

 os.system('ncrename -v z,z_coord -v zi,zi_coord result.nc resultxr.nc')

这允许

 r2 = xr.open_dataset(testdir+'resultxr.nc')

 r = xr.open_dataset(testdir+'result.nc')

失败了。