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

标签 python netcdf python-xarray cdo-climate nco

我有许多坐标(大约 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/

相关文章:

python - 在 matplotlib 中绘制具有相同属性的多个函数

python-2.7 - 使用 python 从 netCDF 读取时间序列

Python 使用 xarray 从 NETCDF 文件中提取多个纬度/经度

scipy - 值错误 : unrecognized engine zarr must be one of: ['scipy' , 'store' ]

python - 内存使用过多 xarray `to_dataframe()`

python - 未找到名为 "interval"的触发器

Python Fabric,为什么 grep 使用 [] 失败

python - 从 netcdf 文件中获取每个月的小时平均值

python - 使用 scipy.interpolate.griddata 对 xarray 中的多维数据进行插值

python - 为什么在 Keras 中 Adam.iterations 总是设置为 0?