簡體   English   中英

當索引名稱有多個維度時,如何使用 xarray 導入 netCDF4 文件?

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

當我嘗試使用 xarray 導入 netCDF4 文件時,出現以下錯誤:

MissingDimensionsError: 'name' 有多個維度,並且與其維度之一('time'、'name')同名。 xarray 不允許使用此類變量,因為它們與用於標注尺寸的坐標相沖突。

但是,我可以使用 netCDF4 python 庫成功導入這些數據,並從中獲取我需要的數據。 問題是這種方法很慢,所以我正在尋找更快的方法並想嘗試 xarray。 這是一個示例文件,以及給我提供相關錯誤的代碼。

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 模型發布的輸出文件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) ;

此處已提議將“rename_var”kwarg 實施到 xr.open_dataset() 作為解決方法,但據我所知,它還沒有實施。

我使用的快速解決方法是在需要的地方從 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')

失敗了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM