标记最后一组项目数据帧

问题描述 投票:0回答:1

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

但是,如果1出现在多行上,那只会将ordernumber放在数据帧的最后一行,而不是放在该给定顺序中的所有行上。

为了显示:

ordernumber   |   lot      |    Last Order of Quarter
------------------------------------------------------
orderA        |   lot1     |     0
orderB        |   lot1     |     1
orderB        |   lot2     |     1

有什么建议?

python pandas dataframe
1个回答
0
投票

示例数据集:

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

然后我们需要生成一个新的布尔列'label'。如果它不验证条件,则该列将为False,而在相反的情况下,该列将为True。注意:将使用int类型以改进计算:

df['label'] = 0
# Assign True conditions to the indexes:
df.loc[indexes,'label'] = 1
© www.soinside.com 2019 - 2024. All rights reserved.