Can I perform dynamic cumsum of rows in pandas?

后端 未结 3 1891
别跟我提以往
别跟我提以往 2020-12-01 22:49

If I have the following dataframe, derived like so: df = pd.DataFrame(np.random.randint(0, 10, size=(10, 1)))

    0
0   0
1   2
2   8
3   1
4            


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 23:31

    simpler approach:

    def dynamic_cumsum(seq,limit):
        res=[]
        cs=seq.cumsum()
        for i, e in enumerate(cs):
            if cs[i] >limit:
                res.append([i,e])
                cs[i+1:] -= e
        if res[-1][0]==i:
            return res
        res.append([i,e])
        return res
    

    result:

    x=dynamic_cumsum(df[0].values,5)
    x
    >>[[2, 10], [6, 8], [9, 4]]
    

提交回复
热议问题