gpt4 book ai didi

python - 从 NETCDF 文件中提取数据的有效方法

转载 作者:行者123 更新时间:2023-12-04 12:14:52 26 4
gpt4 key购买 nike

我有许多坐标(大约 20000),我需要从许多 NetCDF 文件中提取数据,每个文件大约有 30000 个时间步长( future 的气候情景)。使用解决方案 here效率不高,原因是每个 i,j 花费的时间将“dsloc”转换为“dataframe”(查看下面的代码)。
** 示例 NetCDF 文件可以从 here 下载**

import pandas as pd
import xarray as xr
import time

#Generate some coordinates
coords_data = [{'lat': 68.04, 'lon': 15.20, 'stid':1},
{'lat':67.96, 'lon': 14.95, 'stid': 2}]
crd= pd.DataFrame(coords_data)
lat = crd["lat"]
lon = crd["lon"]
stid=crd["stid"]

NC = xr.open_dataset(nc_file)
point_list = zip(lat,lon,stid)
start_time = time.time()
for i,j,id in point_list:
print(i,j)
dsloc = NC.sel(lat=i,lon=j,method='nearest')
print("--- %s seconds ---" % (time.time() - start_time))
DT=dsloc.to_dataframe()
DT.insert(loc=0,column="station",value=id)
DT.reset_index(inplace=True)
temp=temp.append(DT,sort=True)
print("--- %s seconds ---" % (time.time() - start_time))
结果是:
68.04 15.2
--- 0.005853414535522461 seconds ---
--- 9.02660846710205 seconds ---
67.96 14.95
--- 9.028568267822266 seconds ---
--- 16.429600715637207 seconds ---
这意味着每个 i,j 大约需要 9 秒来处理。鉴于大量的坐标和具有大时间步长的 netcdf 文件,我想知道是否有一种可以优化代码的 Pythonic 方式。
我也可以使用 CDO 和 NCO 运算符(operator),但我也发现了使用它们的类似问题。

最佳答案

这是 xarray advanced indexing 的完美用例使用 DataArray 索引。

# make the index on your coordinates the station ID, then convert to a dataset
crd_ix = crd.set_index('stid').to_xarray()

# now, select using the arrays, and the data will be re-oriented to have
# lat and lon indexed by 'stid'
NC.sel(lon=crd_ix.lon, lat=crd_ix.lat, method='nearest')
数据中的其他维度会被忽略,所以如果你的原始数据有维度 (lat, lon, z, time)您的新数据将具有维度 (stid, z, time) .

关于python - 从 NETCDF 文件中提取数据的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69330668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com