yvard yvard - 3 months ago 8
Python Question

How do I Put 2 Conditions in an "if" Statement?

I am trying to set up a function in a way so that it will only execute if two conditions are met: if the variable is greater than some value and smaller than a another value. This is what I have:

########################################################################
def Read_Data(file_location, start_date, end_date):
########################################################################
#imports file
fname = (file_location)
ncfile = netcdf_file(fname,'r');

#reads file and prepares it for usage
juld = np.array( ncfile.variables['JULD'][:] )
juld[juld<start_date] = float('nan')
juld[juld>end_date] = float('nan')

if start_date < juld < end_date:
temp = np.array( ncfile.variables['TEMP'][:] )
temp[temp>45] = float('nan') #eliminates inaccurate data
temp[temp<-10] = float('nan') #eliminates inaccurate data
lon = np.array( ncfile.variables['LONGITUDE'][:] )
lat = np.array( ncfile.variables['LATITUDE'][:] )
ncfile.close()
return temp, lon, lat, juld


I have two functions over this one that define start_time and end_time, as well as a loop that processes the files. As you can see by my
if
statement, I am trying to read a file's data within a range of numbers. When I set it as I did, however, I get this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


I don't understand how to solve this, especially because I am using two variables (start_date, end_date: both are given a numeric value on the previous function).

In short, how to I make my desired "if" statement possible?

Edit: In addition, I want the files that don't meet the criteria to be ignored, and I am not sure if they will be if I don't write an "else" statement.

Answer

First of all, I think you'd wanna look at the min/max value of juld, as it is an array. Try something like:

if max(juld) < start_date or min(juld) > end_date:

I think that should work!

Comments