2

I am trying to get the count of 1s at the tail of a pandas dataframe. From this dataframe:

x 
1
2
3
1
1
1

I want to get the count of 3. If there are no 1s in the tail, then the function should return 0. I could not find any function of pandas to do this. Any ideas?

renakre
  • 8,001
  • 5
  • 46
  • 99

1 Answers1

6

Let's use this:

d1.x[::-1].eq(1).cumprod().sum()
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • 1
  • 1
    That guy doesn't know what he's talking about... this is clever. – piRSquared May 15 '17 at 19:13
  • 1
    Okay. if you run it step by step, you'll see. First thing I do is to reverse order the series, this is because you said "last". Next, I check to see if that value is equal to 1, next I use cumprod to count the 1's at the end of the series, if the value doesn't equal to one it makes the cumprod go to zero. Lastly, you sumup all the values where cumprod returned 1. – Scott Boston May 15 '17 at 19:30
  • 3
    @renakre, do what I did, break it down one piece at a time, and just print out each step. It is fairly straight forward. Magic is that cumprod() will goto and then stay at zero, the first time it sees a false (ie: 0). – Stephen Rauch May 15 '17 at 19:31
  • @StephenRauch Thanks, you've done a great job in explaining better than I. – Scott Boston May 15 '17 at 19:32