【问题标题】:Conditionnal Rolling count条件滚动计数
【发布时间】:2020-07-02 23:52:39
【问题描述】:

这是我的数据框:

score 
1
62
7
15
167
73
25
24
2
76

我想将一个分数与前4个分数进行比较,并计算比当前分数高的分数。

这是我的预期输出:

score   count 
1
62
7
15
167       0
73        1    (we take 4 previous scores : 167,15,7,62 there is just 167 > 73 so count 1)
25        2    
24        3
2         4
76        0

如果有人知道如何做到这一点,欢迎您

谢谢!

【问题讨论】:

标签: python pandas count


【解决方案1】:

我不认为你的输出是根据你的问题。但是,如果您确实只查看前面的 4 元素,那么您可以实现以下内容:

scores = [1, 62, 7, 15, 167, 73, 25, 24, 2, 76]
highers = []

for index, score in enumerate(scores[4:]):
    higher = len([s for s in scores[index:index+4] if score < s])
    print(higher)
    highers.append(higher)

print(highers)
# [0, 1, 2, 3, 4, 0]

然后,您可以将此highers 列表添加为pandas 列:

df['output'] = [0]*4 + highers

请注意,我在这里填充输出的方式是为前四个值分配零。

【讨论】:

  • 你说得对,我的输出不正确,我修复了它。感谢您的帮助,它是完美的
猜你喜欢
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
相关资源
最近更新 更多