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?