首页 > 解决方案 > 标记最后一组项目数据框

问题描述

拥有分为产品批次的销售订单数据集。想要在 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

有什么建议吗?

标签: pythonpandasdataframe

解决方案


示例数据集:

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

推荐阅读