如何使用 XArray 合并特定的 netcdf4

How to use XArray to merge specific netcdf4

背景

我有 2 年的 netcdf4 文件(每天 1 个 netcdf4 文件)。我一直在使用 X-Array 来合并文件,使它们易于使用。所有 netcdf4 文件都遵循相同的命名约定 "YYYYMMDD_data_Nx.nc4.nc"

问题

但是,如果我只想使用数据子集的一个子集,例如 2019 年 1 月 1 日至 2019 年 1 月 31 日之间的文件,我该怎么办。

我目前得到的

import xarray as xr

ds = xr.open_dataset('C:\Users\FILES\*.nc')
df = ds
df.to_csv('export.csv', index=True)

已解决

我查看了 xarray readthedocs 页面,在 open_mfdataset 页面中看到了这个简介。

paths (str or sequence) – Either a string glob in the form "path/to/my/files/*.nc" or an explicit list of files to open. Paths can be given as strings or as pathlib Paths. If concatenation along more than one dimension is desired, then paths must be a nested list-of-lists (see manual_combine for details). (A string glob will be expanded to a 1-dimensional list.)

因此我通过了一个列表

更新和工作代码

import xarray as xr
from datetime import timedelta, date, datetime
import pandas as pd
import numpy as np


# **************
# Date Ranges
# **************
def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)


# Start & End Date
start_date = date(2019, 1, 1)
end_date = date(2019, 1, 31)

# Empty List
filepath = 'C:\Users\USER\FILES\'
filelist = []

# Loop through all MERRA2 files and add the ones we need to the list
for single_date in daterange(start_date, end_date):
    YYYY = single_date.strftime("%Y")
    MM = single_date.strftime("%m")
    DD = single_date.strftime("%d")
    filename = filepath + YYYY + MM + DD + '_data_Nx.nc'

    filelist.append(filename)

# Merge via X-Array and export to csv
ds = xr.open_mfdataset(filelist, combine='by_coords')
df = ds.to_dataframe()
df.to_csv('export.csv', index=True)