【问题标题】:Mark last set of items dataframe标记最后一组项目数据框
【发布时间】:2018-09-02 19:12:26
【问题描述】:

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

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

举例说明:

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

有什么建议吗?

【问题讨论】:

  • 您正在使用此处未列出的列。你能提供一个正确的minimal reproducible example吗?
  • @user791411 您好,请添加您的数据示例。你的插图是期望的输出吗?

标签: python pandas dataframe


【解决方案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

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    相关资源
    最近更新 更多