I have a netCDF file containig daily average temperature over 12 months ( 3D dimension: (lat, lon,time) ) it also contains some invalid data that is assigned to -9999.0 and NaN values. My task is to calculate statistics: monthly average, annual average and return the output as a netCDF file that have the same dimension of the input file and also i have to set back the invalid and NaN data into the output to preserve the initial format but i don't know how can i put the insert data into the corresponding latitude and longitude also when data are invalid or NaN how can i put it in the right position?
Here is a code in python but it generates an empty netCDF....
import netCDF4 as nc
import numpy as np
import numpy.ma as ma
import os
import datetime
warnings.filterwarnings("ignore")
file_name='temperature_moy.nc'
if os.path.isfile(file_name):
os.remove(file_name)
ds = nc.Dataset(file_name, mode="w")
xDim=ds.createDimension("lon", 1087)
yDim=ds.createDimension("lat", 462)
tDim=ds.createDimension("time", None)
var1 = ds.createVariable("MoyTemp", "f4", ("time","lon", "lat",))
times=ds.createVariable("time","i4",("time",))
_Y = ds.createVariable("lat","f4",("lat",))
_X = ds.createVariable("lon","f4",("lon",))
#add netcdf attributes
var1.units = "Celcius"
var1.long_name = "Surface air temperature"
_X.units = "meter"
_X.long_name = "longitude"
_Y.units = "meter"
_Y.long_name = "latitude"
times.units = "seconds since 2018-09-01 00:00:00.0"
times.long_name="time"
d = nc.Dataset('T.nc')
data1_var = d.variables["T2M"]
y=d.variables["lat"]
x=d.variables["lon"]
lat=y[:]
_lat=[i for i in lat]
lon=x[:]
_lon=[j for j in lon]
_X[:] = np.array(_lon)
_Y[:] = np.array(_lat)
#global attributes
ds.description = "netCDF mean temprature"
all_data = data1_var[:]
print(all_data.shape)
data_step1 = data1_var[1,:,:]
list1=[]
list2=[]
result=0
i=0
for x in range(1087):
for y in range(462) :
for t in range(12):
if str(data1_var[t,y,x])!='-9999.0' and str(data1_var[t,y,x])!='nan':
result+=float(str(data1_var[t,y,x]))
list1+=[result/int(data1_var.shape[0])]
result=0
list2+=[list1]
list1=[]
var1[0,:,:] = np.array(list2)