# Using netCDF4 Python climate algorithm?

I have been working in Python with the Acaconda Python distribution to create code that accomplishes the following algorithm:

I have multiple variable netCDF4 files [NCEP Reanalysis tmax(K), tmin(K), shum(%); prate(kg/m^2/s) daily values for an entire year(s)]. Each file spans between (Jan 1 2006- Dec 31 2010). They are 16(lat) by 16(long) grids. Data was downloaded from ESRL: PSD: NCEP Reanalysis. The dimension is time in days. What I'm trying to accomplish is if any given day (n) that satisfies conditions for all variables at each corresponding lat/lon:

tmax and tmin: 18°C ≤ T(n) ≤ 32°C [conversion to K: 291.15K ≤ T(n) ≤ 305.15K]

shum(Q): 20 ≤ Q(n) ≤ 80

prate(R): 1.5mm ≤ R(n) ≤ 20mm [conversion to (kg/m^2/s): R(n) / 84600]

I want to store the number of days PER YEAR in a 4 new netCDF4 - or ArcGIS 10.1 raster/compatible - files (one for each year).

From my understanding, I have not been able to find the correct function to loop through various time steps at specific lat/long/time variables. Perhaps, I have not used the correct phrasing in my search, but I am a novice in programming beyond simple routines.

What you want to do is pretty straightforward in python. Just load the data into numpy arrays (or here a Pandas dataframe) then do some conditional testing with numpy `logical_and` to find out the number of days that your rows match all 3 constraints.

Here's a simple example matching 2 constraints:

``````import pandas as pd
import numpy as np

a = np.arange(10)
d = {'t1':a,'t2':-a}
df = pd.DataFrame(d)

print df

t1  t2
0   0   0
1   1  -1
2   2  -2
3   3  -3
4   4  -4
5   5  -5
6   6  -6
7   7  -7
8   8  -8
9   9  -9

a=np.logical_and(df['t1']>1,df['t1']<5)
b=np.logical_and(df['t2']>-6,df['t2']<-2)

criteria_satisfied = np.logical_and(a,b)
print criteria_satisfied
``````

which produces:

``````0    False
1    False
2    False
3     True
4     True
5    False
6    False
7    False
8    False
9    False
Name: t1, dtype: bool
``````
• I just wanted to add that to get the number of days, you can use `criteria_satisfied.sum()` – DopplerShift Dec 10 '14 at 17:13
• What if I wanted to output these results in new netCDF4 files retaining the integrity of the input coordinates? – Leah Jul 6 '15 at 20:36