如何快速索引NetCDF文件

时间:2018-04-10 20:10:06

标签: python python-3.x indexing netcdf

所以我试图索引NetCDF文件以获取某个网格单元格中的流量数据。我使用的NetCDF文件具有以下特征:

<class 'netCDF4._netCDF4.Dataset'>
root group (NETCDF3_CLASSIC data model, file format NETCDF3):
CDI: Climate Data Interface version 1.6.4 (http://code.zmaw.de/projects/cdi)
Conventions: CF-1.4
dimensions(sizes): lon(3600), lat(1800), time(31)
variables(dimensions): float64 lon(lon), float64 lat(lat), float64 time(time), float32 dis(time,lat,lon)

我有35年以上的这些数据,我正在尝试从单个网格获取数据并创建一个时间序列来比较它做不同模型的预测。我目前用于从网格单元格中提取数据的代码如下所示。

from netCDF4 import Dataset
import numpy as np

root_grp = Dataset(r'C:\Users\wadear\Desktop\ERAIland_daily_dis_198001.nc')
dis = root_grp.variables['dis']
lat = np.round(root_grp.variables['lat'][:], decimals=2).tolist()
lon = np.round(root_grp.variables['lon'][:], decimals=2).tolist()
time = root_grp.variables['time'].shape[0]

lat_index = lat.index(27.95)
lon_index = lon.index(83.55)

for i in range(time):
    print(dis[i][lat_index][lon_index])

现在感觉非常慢,并且需要很长时间才能在超过35年的时间内完成这项工作,并且在执行多个不同的网格单元时,所需​​的时间将真正增加。

是否有工具可以通过更快的I / O或索引来加速此过程?

谢谢!

2 个答案:

答案 0 :(得分:5)

如果你随着时间的推移删除循环并立即访问整个时间序列,你应该节省大量时间,即

dis[:,lat_index,lon_index]

如果在时间维度中应用分块,则可以获得进一步的速度增益。查找nccopy的文档。如果您需要重复访问时间序列,这是值得的。您可能希望在分块之前连接一些NetCDF文件,例如每月 - &gt;年度。这是使用ncrcat实用程序完成的。

另见Chunking Data: Why it Matters

答案 1 :(得分:1)

为什么不先用CDO提取点,然后读入点数据:

cdo remapnn,lon=83.55/lat=27.95 input.nc point_output.nc
如果你没有安装CDO,你可以在ubuntu上安装

sudo apt-get install cdo