Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python loop applying one result to rest of dataframe

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
output 1

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading