我在一个带有一个变量的网格上有一个大约100个时间步长的netcdf文件,该文件在时间步长上累积。我现在有兴趣计算每个时间步长对变量值的贡献(即连续时间步长之差)。
当前我使用以下顺序:
cdo seltimestep,$i ...
,cdo sub $i ${i-1} ...
将每个差异计算为一个新文件cdo mergetime ...
合并为一个结果文件。在我看来,这非常繁琐,并且在性能方面并不理想。由于时间步长很大,因此我无法使用cdo管道,因此需要同时创建许多文件。
有没有更好的解决方案,可以使用cdo(或其他类似nco / ncl的东西)将累积变量转换为时间步长值?
[numpy's diff计算连续条目的差。
我怀疑您的文件中有一个多维变量,所以这是一个通用的示例:
import netCDF4
import numpy as np
ncfile = netCDF4.Dataset('./myfile.nc', 'r')
var = ncfile.variables['variable'][:,:,:] # [time x lat x lon]
# Differences with a step of 1 along the 'time' axis (0)
var_diff = np.diff(var, n=1, axis=0)
ncfile.close()
# Write out the new variable to a new file
ntim, nlat, nlon = np.shape(var_diff)
ncfile_out = netCDF4.Dataset('./outfile.nc', 'w')
ncfile_out.createDimension('time', ntim)
ncfile_out.createDimension('lat', nlat)
ncfile_out.createDimension('lon', nlon)
var_out = ncfile_out.createVariable('variable', 'f4', ('time', 'lat', 'lon',))
var_out[:,:,:] = var_diff[:,:,:]
ncfile_out.close()
xarray
是我选择这种工具的方式:
xarray
如果您想要基于CDO的解决方案,则可以采用一种较短的方法来避免循环并写出很多文件:
import xarray as xr
# Open the netCDF file
ds = xr.open_dataset('./myfile.nc')
# Take the diff along the time dimension
ds['new_variable'] = ds['variable'].diff(dim='time')
# Write a new file
ds.to_netcdf('outfile.nc')
如果您不担心第一个时间步,可以在这里停止,否则您需要解压缩并将其粘贴到文件的开头:
file=your_file_name.nc # just to keep the code shorter in the following :-)
# calculate number of steps in the file:
nstep=`cdo -s ntime $file`
# do difference between steps 2:n and steps 1:(n-1)
cdo sub -seltimestep,2/$nstep $file -seltimestep,1/`expr $nstep - 1` $file diff.nc
[您可以尝试将整个管道作为一个单一管道进行管道传输,尽管这有点混乱(而且我确实发现,过于雄心勃勃的管道传输可能会导致总线错误!]
cdo mergetime -seltimestep,1 $file diff.nc output.nc