I have a MODIS satellite image in netcdf format. I have used certain variables from this image as inputs into a model creating a numpy array called npp
. This array has the same dimensions as the lat and lon of the original file (888,1368)
. I would like to add npp
as a new variable into the original file but I am unclear what I am doing wrong?
import netCDF4 as nc
from netCDF4 import Dataset
# Load input file
file_input = nc.Dataset('A2018066.5d.L3m_OC.nc', 'w', format='NETCDF4')
# view dimensions
print(file_input.dimensions)
"OrderedDict([('lat', <class 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 888
), ('lon', <class 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1368
), ('rgb', <class 'netCDF4._netCDF4.Dimension'>: name = 'rgb', size = 3
), ('eightbitcolor', <class 'netCDF4._netCDF4.Dimension'>: name = 'eightbitcolor', size = 256
)])"
# input file variables.keys
print(file_input.variables.keys())
"odict_keys(['aot_869', 'angstrom', 'Rrs_412', 'Rrs_443', 'Rrs_469', 'Rrs_488', 'Rrs_531', 'Rrs_547', 'Rrs_555', 'Rrs_645', 'Rrs_667', 'Rrs_678', 'chlor_a', 'chl_ocx', 'Kd_490', 'pic', 'poc', 'ipar', 'nflh', 'par', 'lat', 'lon', 'palette'])"
# add npp to input file
file_input.createDimension('latitude',888)
file_input.createDimension('longitude', 1368)
nppvariable = file_input.createVariable('npp', 'int16',('latitude', 'longitude'))
nppvariable[:] = npp[:,:]
But this seems to write over all exisiting variables, losing all the other data?
file_input.variables.keys()
"odict_keys(['npp'])```
Apologies this is my first time handling netcdf4 in python, but why am I losing all the other variables when I use createvariable()
instead of npp
being added as a new variable to the original file? Am I missing a step?
Write mode w
will indeed overwrite your existing NetCDF file, creating a brand new one in it's place.
You're looking for append mode, either a
or r+
:
file_input = nc.Dataset('A2018066.5d.L3m_OC.nc', 'r+', format='NETCDF4')
https://unidata.github.io/netcdf4-python/netCDF4/index.html#netCDF4.Dataset
access mode.
r
means read-only; no data can be modified.w
means write; a new file is created, an existing file with the same name is deleted.a
andr+
mean append (in analogy with serial files); an existing file is opened for reading and writing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.