python - Pandas:基于附加条件的每个类别的 cumsum

标签 python pandas

我有一个以下形式的 pandas 数据框:

id   n_items  paid
 1         5     1
 1         2     0
 1         6     0
 1         1     1
 1         3     0
 1         8     0
 2         7     0
 2         7     1
 3         1     1
 3         5     1
 3         2     1

“id”指定客户 ID,“n_items”表示在特定交易期间购买了多少件商品,“paid”表示客户是否已为该购买付款。对于每个客户 ID,行都是按时间顺序排列的。

对于每一行,我想确定自客户上次付款以来总共购买了多少件商品。输出应如下所示:

id   n_items  paid   cum_days
 1         5     1          5
 1         2     0          2
 1         6     0          8
 1         1     1          9
 1         3     0          3
 1         8     0         11
 2         7     0          7 
 2         7     1         14
 3         1     1          1
 3         5     1          5
 3         2     1          2

我找到了this帖子,它解决了类似的问题,但我还没有设法为此目的修改它。

最佳答案

使用cumsum计算组变量来识别模式(自上次付款以来),然后计算每个ID的n_items的累积和和未付款期:

df['cumdays'] = df.groupby([
                    df.id, df.paid.cumsum().shift().fillna(0)
                ]).n_items.cumsum()
df

enter image description here

关于python - Pandas:基于附加条件的每个类别的 cumsum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44552826/

相关文章:

python - 在 template.render 中关闭自动转义

python - 以编程方式将 "decorators"添加到 python 函数

python - 使用 BeautifulSoup 抓取 ajax 网站

python - SciPy - 点积在稀疏和密集矩阵上的推广

python - GroupBy 结果到列表字典

python - Pandas:如何删除系列中的非字母数字列

python - 根据 groupby 之后其他列中的值之间的数据帧范围对单独的列求和

python - PyQt5中如何让小部件随窗口缩放?

python - 如何获取 python 中具有最大值的列的列?

python - Pandas 按值分组并合并行