0
votes

I have created a dataframe (boolean values) from a timeseries which (true on a certain date if value is above x, false if value is below). I am trying to loop into this dataframe- whenever I encounter a true value I want to update the counter; if false I want to break and print the updated counter. It looks like this, but the while loop does not break - any ideas of what I am missing here? Thanks in advance

k=0
dataa='2019-11-01'
for index in df_resz[dataa:].iterrows():
    while (df_resz.loc[dataa,'bool_resz']==True):
            k=k+1
    else:
        break
print (k)
2
Please tag the language you're using to get the appropriate help you need (you can click edit to add the tag) - Nick Parsons
Why would df_resz.loc[dataa,'bool_resz'] ever change from True to False once you're inside the while loop??? Also, your break statement would technically end the for loop if it is ever reached, so why have a for loop to begin with??? - goodvibration
Any suggestions to achieve what I have in mind then? Thanks - freddie_mercury
@NickParsons thanks Nick it's Python - freddie_mercury

2 Answers

0
votes

If I understood your problem correctly, your goal is to iterate a dataframe column and sum the True values until you find a False. If so:

>>> dict = {'value':[True, True, False, True]}
>>> df = pd.DataFrame(dict)
>>> df
   value
0   True
1   True
2  False
3   True
>>> counter = 0
>>> for i, j in df.iterrows():
...     if j.value == True:
...             counter += 1
...     else:
...             break
... 
>>> counter
2
0
votes

Let me first explain why the while loop does not break. You loop through your data, at the first value that is true you start the while loop, but in the while loop this value won't be updated. So you remain at the same True value in your data while updating k infinitely.

To solve your problem just use a for loop and an if statement:

test = pd.Dataframe({'value':[True, False, True]})
k = 0

for i in test.index():
    if test(i) == True:
        k += 1