如何更新部分 netCDF 文件?

How to update portion of the netCDF file?

我有 1500 行和 2000 列的 netCDF 文件。其中很少有不同位置的数据不一致。我想用 NoData 值更新这种不一致。在研究过程中,我发现了很多答案,其中有人想将变量值 above/below 更新到某个阈值。例如:

#------ Research-----

dset['var'][:][dset['var'][:] < 0] = -1

#-----------------

由于不一致的值与数据值匹配,因此无法根据低于/高于某个阈值更新不一致。

我的方法一:

ncfile   =   r'C:\abcd\55618_12.nc'
variableName =  'MAX'   

fh = Dataset(ncfile, mode='r+')

for i in range(500,600,1):
    for j in range(200,300,1):
        fh.variables[variableName][i][j] = -99900.0 # NoData value
        #--- or 
        #fh.variables[variableName][i:j] = -99900.0

fh.close()

方法二:

fh = Dataset(ncfile, mode='r')
val = fh.variables[variableName]

for i in range(500,600,1):
    for j in range(200,300,1):
        val[i][j] = -99900.0

fh = Dataset(ncfile, mode='w') #(ncfile, mode='a')(ncfile, mode='r+')
fh.variables[variableName] = val
fh.close()

结果: 脚本成功完成处理。但是不要更新.nc 文件。

朋友们,非常感谢您的帮助。

以下方法对我有用:

import netCDF4 as nc
import numpy as np

ncfile   =   r'C:\abcd\55618_12.nc'
variableName =  'MAX'

fh = nc.Dataset(ncfile, mode='r')
val = fh.variables[variableName][:]
fh.close()

print type (val)

for i in range(500,600,1):
    for j in range(200,300,1):
        #print i,j
        val[i][j] = -99900.0
        if val[i][j]> -99900.0:
            print val[i][j]


fh = nc.Dataset(ncfile, mode='r+')
fh.variables[variableName][:]= val
fh.close()

数据是否在 lat/lon 网格上?如果是这样,使用 cdo:

从命令行执行可能更容易
cdo setclonlatbox,FillValue,lon1,lon2,lat1,lat2  infile.nc outfile.nc

其中 FillValue 是您的缺失值,在您的情况下似乎是 -99900.0。