To enable conditional calculations with an equation instead of only calculating with a constant I have included a conditional iteration for a variable with shape of (month,lats,lons) based on the code by @jhamman as follows:
import netCDF4 as nc
import numpy as np
import time
Tmin = -1.7
Tmax = 4.9
perc = (Tmax-Tmin)/100
lats = np.arange(0,384,1)
lons = np.arange(0,768,1)
months = [0,1]
dset = nc.Dataset('path/file.nc', 'r+')
start = time.time()
dset['var'][:][dset['var'][:] < Tmin] = 100
step1 = time.time()
print('Step1 took: ' + str(step1-start))
dset['var'][:][dset['var'][:] > Tmax] = 0
step2 = time.time()
print('Step2 took: ' + str(step2 - step1))
#start iteration of each dimension to alter individual values according to equation new_value = 100-((Old_value +1.8)/1%)
for m in months:
newstart = time.time()
for i in lats:
step3 = time.time()
print('month lats lat layer '+str(i)+' took: '+str(step3-newstart) +'s')
for j in lons:
if dset['var'][m,i,j] < Tmax and dset['var'][m,i,j] > Tmin:
dset['var'][m,i,j] = 100-((dset['var'][m,i,j]+1.8)/perc)
end = time.time()
print('One full month took: ' + str(end-start) +'s')
dset.close()
The problem however is that it becomes a very slow code.
Step1 took: 0.0343s
Step2 took: 0.0253s
month lats lat layer: 0.4064s
One full month took 250.8082s
This is logic due to the iterations. I was wondering however if any of you have the idea how to speed this up a bit. Are the iterations really necessary for this goal?