【问题标题】:How to import netCDF4 file with xarray when index names have multiple dimensions?当索引名称具有多个维度时,如何使用 xarray 导入 netCDF4 文件?
【发布时间】:2019-08-02 05:12:41
【问题描述】:

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

MissingDimensionsError: 'name' 有多个维度且名称与其维度之一相同('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

【问题讨论】:

  • 我认为这不太可能在 xarray 中工作。正如您收到的错误所示,您有一个与二维坐标共享名称的维度。虽然 netCDF 支持这一点,但 xarray 不支持。最简单的解决方法可能是在使用 xarray 打开之前重命名 netcdf 文件中的维度(或坐标)。
  • 我担心是这样。那是我读到的,但我希望有一个解决方法。唯一的问题是我有 383 个这些文件,而且我不知道如何快速重命名它们。当您对 383 个文件(大约 3 小时)进行 20 秒的读取时,补偿时间会变得很昂贵。

标签: python python-xarray netcdf4


【解决方案1】:

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

例如,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')

失败了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多