更改变量的netcdf文件的值

时间:2017-02-17 15:19:37

标签: python netcdf

我有一个三维的大型netcdf文件。我想用netcdf文件中的变量LU_INDEX替换所有值为10的值。

我写了这个python脚本,但它似乎没有用。

filelocation = 'D:/dataset.nc'

ncdataset = nc.Dataset(filelocation,'r')
lat           = ncdataset.variables['XLAT_M'][0,:,:]
lon           = ncdataset.variables['XLONG_M'][0,:,:]
lu_index     = ncdataset.variables['LU_INDEX'][0,:,:]
lu_index_new = lu_index
ncdataset.close()

nlat,nlon=lat.shape

for ilat in range(nlat):
    for ilon in range(lon):
        if lu_index == 10:
          lu_index_new[ilat,ilon] = 2

newfilename = 'D:/dataset.new.nc'
copyfile(ncdataset,newfilename)


newfile     = nc.Dataset(newfilename,'r+')
newfile.variables['LU_INDEX'][0,:,:]   = lu_index_new
newfile.close()

我收到错误:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我对python不是很有经验,所以如果有更简单的方法,我们非常欢迎您发表评论。

3 个答案:

答案 0 :(得分:5)

您可以尝试NCO

ncap2 -s'其中(LU_INDEX == 10)LU_INDEX = 2'in.nc out.nc

答案 1 :(得分:2)

我按照以下方式解决了这个问题:

import netCDF4 as nc
import numpy as np

pathname = 'D:'
filename = '%s/dataset.nc'%pathname
ncfile = nc.Dataset(filename,'r+')
lu_index = ncfile.variables['LU_INDEX'][:]
I = np.where(lu_index == 10)
lu_index[I] = 2
ncfile.variables['LU_INDEX'][:] = lu_index
filename.close()

print 'conversion complete'

答案 2 :(得分:2)

使用np.array可能不适用于具有以下错误的非常大的数据集

“ValueError:数组太大; arr.size * arr.dtype.itemsize大于最大可能大小。”

除了NCO之外,CDO可以是一个很好的工具,对我而言,速度非常快。

CDO setvals,10,2 in.nc out.nc

当您必须在同一个nc文件中替换多个变量中的值时(例如,替换缺失值表示),它会特别快。 可以使用“setrtoc”代替setval来指定范围。