使用 Xarray 从 netCDF 文件中提取数据到高数据帧中的有效方法

Efficient method to extract data from netCDF files, with Xarray, into a tall DataFrame

我有一个包含大约 350 个坐标的列表,这些坐标是指定区域内的坐标,我想使用 Xarray 从 netCDF 文件中提取这些坐标。如果相关,我正在尝试从特定地表模型中提取 SWE(雪水当量)数据。

我的问题是这个 for 循环需要很长时间才能遍历列表中的每个项目并获取相关的时间序列数据。也许在某种程度上这是不可避免的,因为我必须为每个坐标实际从 netCDF 文件加载数据。我需要帮助的是以任何可能的方式加速代码。现在,这需要很长时间才能 运行,需要 3 个多小时,并且计算得更精确。

这是我到目前为止所做的一切:

import xarray as xr
import numpy as np
import pandas as pd
from datetime import datetime as dt

1)首先,打开所有文件(1915-2011年的每日数据)。

df = xr.open_mfdataset(r'C:\temp\*.nc',combine='by_coords')

2) 将我的位置缩小到美国大陆内的一个较小的盒子

swe_sub = df.swe.sel(lon=slice(246.695, 251), lat=slice(33.189, 35.666))

3)我只想提取每个月的第一个每日值,这也缩小了时间序列。

swe_first = swe_sub.sel(time=swe_sub.time.dt.day == 1)

现在我想加载我的坐标列表(恰好在 Excel 文件中)。

coord = pd.read_excel(r'C:\Documents\Coordinate_List.xlsx')
print(coord)
lat = coord['Lat']
lon = coord['Lon']
lon = 360+lon
name = coord['OBJECTID']

以下 for 循环遍历我的坐标列表中的每个坐标,提取每个坐标处的时间序列,并将其滚动到一个 tall DataFrame 中。

Newdf = pd.DataFrame([])
for i,j,k in zip(lat,lon,name):
    dsloc = swe_first.sel(lat=i,lon=j,method='nearest')
    DT=dsloc.to_dataframe()

    # Insert the name of the station with preferred column title:
    DT.insert(loc=0,column="Station",value=k)
    Newdf=Newdf.append(DT,sort=True)

非常感谢大家提供的任何帮助或建议!

好吧,我想通了。结果我需要先将我的数据子集加载到内存中,因为默认情况下 Xarray "lazy loads" 进入数据集。

这是我为使其正常工作而修改的代码行:

swe_first = swe_sub.sel(time=swe_sub.time.dt.day == 1).persist()

这里是 link 我发现对这个问题有帮助:

https://examples.dask.org/xarray.html

我希望这也能帮助其他人!