Your code relies on a number of implicit assumptions:...
Assumptions that are savely ok considering the OP dataset.
And that was why I said ..using your dataset.. i.e that of the OP in my previous reply, which I don't suppose have anything which follows "THE" assumptions, you stated. Except the OP has said otherwise to you privately.
If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me
I did not want to say that anything is wrong with your code. I only thought it useful to highlight the assumptions which you were aware of but probably not every reader of the thread. And I have no additional information about the question.