如何为拍卖场景的DataFrame新增非逐行计数的已售商品数量列
实现方案
逻辑说明
统计逻辑的核心是按拍卖场次独立计数,同一场次内每次在售商品编号发生变化时,累计已售数加1:
- 同一
id.product_permutation(拍卖场次)的计数相互独立,新场次开启时计数重置为0 - 同场次内,
property.product与上一轮次不同则代表上一件商品售出,计数+1 - 初始轮次(同场次第一行)无已售商品,计数为0
前置操作
先确保数据按「场次+迭代轮次」的时间顺序排序,避免顺序异常导致计数错误:
import pandas as pd df = df.sort_values(by=['id.product_permutation', 'id.iteration']).reset_index(drop=True)
核心代码
通过分组移位对比+累计求和实现目标列生成:
df['amount_of_sold_items'] = df.groupby('id.product_permutation')['property.product']\ .apply(lambda x: (x != x.shift()).cumsum() - 1)
效果验证
以下面的测试数据为例:
| id.product_permutation | id.iteration | property.product | property.price | amount_of_sold_items |
|---|---|---|---|---|
| 1 | 1 | 1 | 100 | 0 |
| 1 | 2 | 1 | 120 | 0 |
| 1 | 3 | 2 | 90 | 1 |
| 1 | 4 | 2 | 110 | 1 |
| 1 | 5 | 3 | 200 | 2 |
| 1 | 6 | 3 | 230 | 2 |
| 2 | 1 | 3 | 150 | 0 |
| 2 | 2 | 1 | 180 | 1 |
计算逻辑与预期结果完全匹配。
内容的提问来源于stack exchange,提问作者deputy-chief-hardy
相关产品推荐
相关产品推荐

