【问题标题】:How to use XArray to merge specific netcdf4如何使用 XArray 合并特定的 netcdf4
【发布时间】:2020-01-29 08:29:41
【问题描述】:
背景
我有 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)
【问题讨论】:
标签:
python
merge
python-xarray
netcdf4
【解决方案1】:
解决了
我查看了 xarray readthedocs 页面,在 open_mfdataset 页面中看到了这个简介。
paths (str or sequence) – 格式中的字符串 glob
“path/to/my/files/*.nc”或要打开的文件的明确列表。路径
可以作为字符串或 pathlib 路径给出。如果串联
需要多个维度,则路径必须是嵌套的
列表列表(有关详细信息,请参阅 manual_combine)。 (字符串 glob 将是
展开为一维列表。)
因此我通过了一个列表
更新和工作代码
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)