I’m relatively new to python. I have a data frame containing rainfall data. I would like to create function with a ‘scenario A’ that will increase the longest dry period (days with rainfall <= 0) by one day and another ‘scenario B’ that will increase the period by two days. The codes below shoes how far I have come. It does the function I want for scenario A, but now I don’t know how to incorporate scenario B into the function, and still get the outputs (specified in code below) that I need for both scenarios. Can anyone help please?
def increase_dry_period(df):
# Initialize variables
season_length = df.shape[0] # Specify season length as length of row entries
max_counter = 0 # Value of longest dry period
counter = 0 # Cumulative counter for daily dry days
start_row_dry_period = 0 # Starting index of longest dry period
end_row_dry_period = 0 # Ending index of longest dry period
# Convert all the rainfall events <= 1 mm to 0 mm
idx_zero = df['PRECIP'] <= 1
df.loc[idx_zero,'PRECIP'] = 0
# Iterate through all the rows of percipitation
for k,row in df.iterrows():
P = row['PRECIP']
# Set condition that counts longest dry period (days where rainfall = 0)
if P == 0:
# Count days when condition is met
counter += 1
# Identify the longest dry period (maximum number of dry days)
if counter > max_counter:
max_counter = counter
# Identify the day before and day afer the longest dry period
if k < season_length-1:
# Store start and end of longest dry period
start_row_dry_period = k-counter+1
end_row_dry_period = k
max_counter_period = (end_row_dry_period - start_row_dry_period)
# Change the day after the longest dry period to zero (if still within growing season period)
df.loc[k+1, 'PRECIP'] = 0.0
elif k >= season_length-1:
# Store index of start and end days of longest dry period
start_row_dry_period = k-counter+1
end_row_dry_period = k
# Define number of days of the longest dry period
max_counter_period = (end_row_dry_period - start_row_dry_period)
# If last day of longest dry period = last day of entire growing season,
# change the day before longest dry period to zero
df.loc[k-counter, 'PRECIP'] = 0.0
else:
# Reset the counter to zero when it encounters a rainy day
counter = 0
# Save the desired variables into one giant dictionary
output = {'df': df, 'start': df.loc[start_row_dry_period, 'TIMESTAMP'],
'end': df.loc[end_row_dry_period, 'TIMESTAMP'],
'length': max_counter_period}
# Return the dictionary above as the output of the function
return output
I tried to add an argument that takes in the both the dataframe containing rainfall data (df) and the list containing values for how many days I want to increase the longest dry period by in scenario A and scenario B. But I am not able to do that:
def increase_dry_period(df, no_of_days):
# no_of_days = [1,2]
Igwe Kelechi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.