python - 标记最后一组项目数据框
问题描述
拥有分为产品批次的销售订单数据集。想要在 Pandas / Python 中为给定年份内最后一个订单的所有批次应用标志。有什么建议吗?
目前有:
masterDF['FLAG'] = masterDF.groupby(by=['id','year'],as_index=False)['ordernumber'].nth(-1)
masterDF['LAST_ORDER_OF_QUARTER'] = np.where(masterDF['FLAG'].isnull(),0,1)
但这只会将 a1
放在数据框的最后一行上,如果出现在多行上,则不会放在给定顺序内的所有行上。ordernumber
为了显示:
ordernumber | lot | Last Order of Quarter
------------------------------------------------------
orderA | lot1 | 0
orderB | lot1 | 1
orderB | lot2 | 1
有什么建议吗?
解决方案
示例数据集:
event_id,type,timestamp
asd12e,click,12322232
asj123,click,212312312
asd321,touch,12312323
asdas3,click,33332233
sdsaa3,touch,33211333
我们想为列“id_type”中的最后一个订单应用一个标签。首先,我们将最后一个类型顺序分配给索引。为了做到这一点:
indexes = df.drop_duplicates(subset='type',keep='last').index
然后我们需要生成一个新的布尔列“标签”。如果不验证条件,则此列将为 False,反之则为 True。注意:将使用 int 类型来改进计算:
df['label'] = 0
# Assign True conditions to the indexes:
df.loc[indexes,'label'] = 1
推荐阅读
- pdf-generation - Ghostscript : ps to pdf - 保持方向
- javascript - 使用 progressbar.js 在我的进度圈上添加限制栏
- tfs - TFS 2018 代码搜索
- node.js - Mongoose 查找设置,例如。如果位置是全部显示所有结果不是位置:“全部”
- python - 用于组合异步迭代器的映射、过滤器和迭代工具
- html - 在 ionic 的 html 标签中使用未定义的属性
- mysql - 使用 mysql 数据通过 Elasticsearch 实现搜索
- websocket - Web 套接字和动态 CRM
- xamarin - 以 xamarin 形式获取日期和时间
- postgresql - 根据标准选择差异