Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing value of a netcdf file for a variable

Tags:

python

netcdf

I have a large netcdf file which is three dimensional. I want to replace for the variable LU_INDEX in the netcdf file all the values 10 with 2.

I wrote this python script to do so but it does not seem to work.

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()

I get the error:

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

I am not a very experienced with python, so if there is a more easier way to do this you are very welcome to comment.

like image 214
Gijs Koetsenruijter Avatar asked Oct 17 '25 22:10

Gijs Koetsenruijter


1 Answers

You might try NCO

ncap2 -s 'where(LU_INDEX == 10) LU_INDEX=2' in.nc out.nc
like image 195
Charlie Zender Avatar answered Oct 20 '25 12:10

Charlie Zender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!