I have made a loop that is supposed to check if a value and the next one are the same, and if they are, append a new list. this will then loop through values from a dataframe until complete.
At current, the code works for the first two values in the dataframe, but then applies the result to the rest of the dataframe instead of moving onto the next in the list.
below is the code required for this:
import numpy as np
import pandas as pd
import math
pww = 0.72
pdd = 0.62
pwd = 1 - pww
pdw = 1 - pdd
lda = 1/3.9
rainfall = pd.DataFrame({
"Day": range(1, 3651),
"Random 1": np.random.rand(3650),
"Random 2": np.random.rand(3650)
})
state = [1]
for i in range(1, len(rainfall)):
prev_state = state[-1]
random_value = rainfall.loc[i, "Random 2"]
if prev_state > 0:
new_state = 1 if random_value < pww else 0
else:
new_state = 1 if random_value < pdw else 0
state.append(new_state)
rainfall["State"] = state
pww_prob = []
for i in state:
next_state = state[+1]
states = rainfall.loc[i, "State"]
if states >0 and next_state >0:
pwet = 1
else:
pwet = 0
pww_prob.append(pwet)
rainfall["pww"] = pww_prob
print(rainfall.loc[:, ["State", "pww"]])
the output for one run of this is:

for these results, the output in the pww column should be 1, 0, 0, 0, 0 … 0, 0, 1, 1, 1.
for i in state:
next_state = state[+1]
states = rainfall.loc[i, "State"]
if states >0 and next_state >0:
pwet = 1
else:
pwet = 0
pww_prob.append(pwet)
this is the main loop that is not working as intended.
Thanks in advance.
>Solution :
try this:
for i in range(len(rainfall)):
if i < len(rainfall) - 1:
next_state = state[i+1]
else:
next_state = 0
current_state = rainfall.loc[i, "State"]
if current_state > 0 and next_state > 0:
pwet = 1
else:
pwet = 0
pww_prob.append(pwet)