首页 > 解决方案 > 使用 Xarray 从 netCDF 文件中提取数据到高 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 循环遍历我的坐标列表中的每个坐标,提取每个坐标的时间序列,并将其滚动到一个高大的 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)

我将非常感谢你们提供的任何帮助或建议!

标签: pythonpandasperformancenetcdfpython-xarray

解决方案


好吧,我想通了这一点。原来我需要先将我的数据子集加载到内存中,因为默认情况下 Xarray “延迟加载”到 Dataset 中。

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

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

这是我发现对这个问题有帮助的链接:

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

我希望这对其他人也有帮助!


推荐阅读