【问题标题】:reset cumulative sum based on another column根据另一列重置累积总和
【发布时间】:2020-11-28 12:25:48
【问题描述】:

有很多与条件累积和相关的查询和答案(Cumsum Reset based on a condition in PandasReset Cumulative sum base on condition PandasCumsum Reset based on a condition in Pandas)。但我无法解决我面临的问题。以下是我拥有的部分数据,要求是保持对“类型”和相应累积总和的变化进行计数。

  type sale
    y   10   
    y   20   
    y    5   
    n   30   
    n   20   
    n    5   
    y   10   
    y   40   
    y   15   

我的要求是获取类型变化和累积销售的序列计数,如下所示。

   type sale tp_cum cum_sale
    y   10    1      10
    y   20    1      30
    y    5    1      35
    n   30    2      30
    n   20    2      50 
    n    5    2      55
    y   10    3      10
    y   40    3      50
    y   15    3      65

我尝试了以下代码的各种修改,但不完全符合要求。请帮忙。

sales['cum_sale'] = stock.groupby('type')['sale'].cumsum()

数据框:

df = pd.DataFrame([["y",10 ], 
["y",20  ],
["y",5  ],
["n",30   ],
["n",20   ],
["n",5 ],
["y",10  ], 
["y",40  ],
["y",15 ]],columns = ["type","sale"])

【问题讨论】:

  • 我认为循环遍历行效率太低,或者有其他东西反对这样做?

标签: python pandas cumulative-sum


【解决方案1】:

这里有一个选项,你先创建tp_cum列然后cumsum()

import pandas as pd
import numpy as np

df = pd.DataFrame([["y",10 ], 
["y",20  ],
["y",5  ],
["n",30   ],
["n",20   ],
["n",5 ],
["y",10  ], 
["y",40  ],
["y",15 ]],columns = ["type","sale"])

df["type2"] = np.cumsum((df["type"] != df["type"].shift(1)))
df["cum_sale"] = df[["sale","type2"]].groupby("type2").cumsum()
df

输出:

    type    sale    type2  cum_sale
0   y       10      1      10
1   y       20      1      30
2   y       5       1      35
3   n       30      2      30
4   n       20      2      50
5   n       5       2      55
6   y       10      3      10
7   y       40      3      50
8   y       15      3      65

【讨论】:

  • 你也可以,df.groupby((df.type != df.type.shift(1)).cumsum())['sale'].cumsum()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 2020-10-16
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
相关资源
最近更新 更多