【问题标题】:How to read data only for a specified period with netCDF4 module?如何使用 netCDF4 模块仅读取指定时间段的数据?
【发布时间】:2018-07-22 07:09:52
【问题描述】:

我想读取指定时间段的 netCDF 数据。 我尝试读取的ncfile被命名为file.ncncdump -c file.nc的部分信息是

dimensions:
lat = 1 ;
lon = 1 ;
time = UNLIMITED ; // (744 currently)
variables:
float lat(lat) ;
    lat:units = "degrees_north" ;
    lat:long_name = "latitude" ;
float lon(lon) ;
    lon:units = "degrees_east" ;
    lon:long_name = "longitude" ;
double time(time) ;
    time:units = "hours since 2015-07-01 01:00:00" ;
    time:long_name = "time" ;
double rain(time, lat, lon) ;
    rain:_FillValue = -999000000. ;
    rain:units = "K" ;
    rain:standard_name = "temperature" 
data:

lat = 1 ;
lon = 1 ;
time = -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, ... 
737, 738, 739, 740, 741, 742 ;

这是我读取这个 ncfile 的脚本。

import netCDF4

nc = netCDF4.Dataset(file.nc, 'r')
data = nc.variables['temperature'][:] #I want to read between 2015-07-20 00:00 to 2015-07-24 23:00

我想在检测开始日期和结束日期的特定时间段之间进行阅读。该怎么做呢?

【问题讨论】:

  • 我强烈建议为此使用 xarray;参见例如这个问题/答案展示了使用 xarray 选择时间段是多么容易:stackoverflow.com/questions/51323528/…
  • 它可以归结为像import xarray as xr; nc = xr.open_dataset(file.nc, 'r'); p = nc.sel(time=slice('2015-07-20 00:00', '2015-07-24 23:00'))这样简单的东西
  • @Bart 感谢您的回复。顺便说一句,type(p)<xarray.Dataset>。你知道如何提取数据(温度数据)并转换为numpy吗?
  • p['temperature'].values 这样的东西应该会给你一个普通的 Numpy 数组。
  • @Bart 我明白了!非常感谢。

标签: python netcdf netcdf4


【解决方案1】:

正如@Bart 建议的那样,xarray 是要走的路。这是不带 xarray 的答案。 NetCDF4.date2index() 就是答案。

import netCDF4
import dateutil.parser

nc = netCDF4.Dataset(file.nc, 'r')

# all_times variable includes the time:units attribute
all_times = nci.variables['time']

sdt = dateutil.parser.parse("2015-07-20T00:00:00")
edt = dateutil.parser.parse("2015-07-24T23:00:00")

st_idx = netCDF4.date2index(sdt, all_times)
et_idx = netCDF4.date2index(edt, all_times)

data = nc.variables['temperature'][st_idx:et_idx+1,:] #I want to read between 2015-07-20 00:00 to 2015-07-24 23:00

【讨论】:

  • 不知道date2index,不错的选择。我的 NetCDF4 解决方案(我不敢发布)稍微不那么优雅 ;-)
  • @Eric Bridger 我也按照你的建议做了。感谢您的回复。
猜你喜欢
  • 2014-05-31
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 2016-03-17
  • 2019-09-24
  • 2017-10-04
  • 2019-11-13
相关资源
最近更新 更多