我有大约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)
非常感谢您提供的任何帮助或建议!
好吧,我想出了这个。原来我需要先将数据子集加载到内存中,因为默认情况下Xarray会将数据集“延迟加载”到Dataset中。
这是我为了使其正常工作而修改的代码行:
swe_first = swe_sub.sel(time=swe_sub.time.dt.day == 1).persist()
这是我发现对此问题有帮助的链接:
https://examples.dask.org/xarray.html
我希望这也能帮助其他人!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句