标记最后一组项目数据框

时间:2018-08-30 21:02:13

标签: python pandas dataframe

有一个销售订单数据集,该销售订单被划分为产品批次。希望在给定年份中使用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

有什么建议吗?

1 个答案:

答案 0 :(得分: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
相关问题