我有一个约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.orgxarray.html
希望这也能帮助到别人!