Python: How to iterate over the indexes of a variable in a 'for loop'

Somehow iterating over a multi-indexed dataframe can be tricky.
I wanted to access a value related to an employee in the current and in the three subsequent periods of time. I needed to test the value of each period in an 'if statement' that would decide the next employee's task (scheduling problem). However, the if condition returned a Series (containing the index levels) instead of a single value and then the program was not able to give a True/False response. And the program crashed.

So so weird, but it turns out, it was just a syntax issue.
#The current and subsequent periods
p_prox = [16 17 18 19]

#b_atual is a magnitude to compare the "value" associated to each employee in each period of time. Let's suppose b_atual = 5.

#iterator
p_count = 0

#dataframe 'rank'
rank = 
 employee  Period  value
 Juli       16      9
 Juli       17      9
 Juli       18      5
 Juli       19      9

#This is the loop:
for p in p_prox:    
    while p_count < 6: 
        if rank.loc[(employee,p)].iloc[0] == b_atual:
            task[employee][p] =  1
        p_count = p_count + 1

Long story short, this is how we access a single value of a multi-indexed dataframe:
df.loc[(index1,index2)].iloc[0]
Note that we are in fact accessing the value in the first row of the returned Series. But as long as we know there will be only one value for each employee in each period of time, it works well.

No comments:

Post a Comment

Python: How to iterate over the indexes of a variable in a 'for loop'

Somehow iterating over a multi-indexed dataframe can be tricky. I wanted to access a value related to an employee in the current and in the...