【问题标题】:Python - cumulative sum until sum matches an exact numberPython - 累积总和,直到总和匹配一个确切的数字
【发布时间】:2020-08-24 10:32:04
【问题描述】:

我在 Python Pandas df 中有一列数字:1,8,4,3,1,5,1,4,2 如果我创建一个累积总和列,它会返回累积总和。如何只返回累积总和达到 20 个跳过数字且累积总和超过 20 的行?

+-----+-------+------+
| Var | total | cumu |
+-----+-------+------+
| a   |     1 |    1 |
| b   |     8 |    9 |
| c   |     4 |   13 |
| d   |     3 |   16 |
| e   |     1 |   17 |
| f   |     5 |   22 |
| g   |     1 |   23 |
| h   |     4 |   27 |
| i   |     2 |   29 |
+-----+-------+------+

期望的输出:

+-----+-------+------+
| Var | total | cumu |
+-----+-------+------+
| a   |     1 |    1 |
| b   |     8 |    9 |
| c   |     4 |   13 |
| d   |     3 |   16 |
| e   |     1 |   17 |
| g   |     1 |   18 |
| i   |     2 |   20 |
+-----+-------+------+

【问题讨论】:

标签: python pandas


【解决方案1】:

如果我正确理解了您的问题,您只想跳过使您超过 20 的累积总和的值:

def acc(total):
    s, rv = 0, []
    for v, t in zip(total.index, total):
        if s + t <= 20:
            s += t
            rv.append(v)
    return rv

df = df[df.index.isin(acc(df.total))]
df['cumu'] = df.total.cumsum()
print(df)

打印:

  Var  total  cumu
0   a      1     1
1   b      8     9
2   c      4    13
3   d      3    16
4   e      1    17
6   g      1    18
8   i      2    20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 2020-03-30
    • 2021-10-28
    • 2014-05-11
    • 2019-02-15
    • 2020-08-20
    相关资源
    最近更新 更多