Pandas 分组累计计数条件

huangapple go评论101阅读模式
英文:

Pandas Grouped Cumulative Count with Condition

问题

我有一个带有年份、用户ID和积分的pandas数据框。我试图计算下面的第四列 - 用户每年积分为0或更少的连续年份数。

示例数据框:

年份 用户ID 积分 连续计数
2010 13 10 0
2011 13 0 0
2012 13 -5 1
2013 13 0 2
2014 13 4 0
2010 77 -9 0
2011 77 -1 1
2012 77 5 0
2013 77 0 0
2014 77 -1 1
英文:

I have a pandas df with Year, UserID, and Points. I'm trying to derive the fourth column below - a running count of the number of consecutive years a user has 0 points or less per year.

Ex Df

Year UserID Points RunningCount
2010 13 10 0
2011 13 0 0
2012 13 -5 1
2013 13 0 2
2014 13 4 0
2010 77 -9 0
2011 77 -1 1
2012 77 5 0
2013 77 0 0
2014 77 -1 1

答案1

得分: 1

你可以先为连续的正负点创建一个分组列,然后按照该分组使用cumcount

  1. neg_group = df.Points.le(0).diff().ne(0).groupby(df.UserID).cumsum()
  2. df.groupby([df.UserID, neg_group]).cumcount()
英文:

You can create a group column for consecutive positive or negative points first and then do a cumcount by the group:

  1. neg_group = df.Points.le(0).diff().ne(0).groupby(df.UserID).cumsum()
  2. neg_group
  3. 0 1
  4. 1 2
  5. 2 2
  6. 3 2
  7. 4 3
  8. 5 1
  9. 6 1
  10. 7 2
  11. 8 3
  12. 9 3
  13. Name: Points, dtype: int64
  14. df.groupby([df.UserID, neg_group]).cumcount()
  15. 0 0
  16. 1 0
  17. 2 1
  18. 3 2
  19. 4 0
  20. 5 0
  21. 6 1
  22. 7 0
  23. 8 0
  24. 9 1
  25. dtype: int64

huangapple
  • 本文由 发表于 2023年4月17日 08:54:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定