【问题标题】:Pandas - Subtract min date from max date for each groupPandas - 从每个组的最大日期中减去最小日期
【发布时间】:2018-06-08 01:58:54
【问题描述】:

我想将每个 customer_id 的最大日期减去最小日期的结果添加到此表中

输入:

action_date customer_id
 2017-08-15       1
 2017-08-21       1
 2017-08-21       1
 2017-09-02       1
 2017-08-28       2
 2017-09-29       2
 2017-10-15       3   
 2017-10-30       3
 2017-12-05       3

得到这张桌子

输出:

action_date customer_id    diff
 2017-08-15       1         18
 2017-08-21       1         18
 2017-08-21       1         18
 2017-09-02       1         18
 2017-08-28       2         32
 2017-09-29       2         32
 2017-10-15       3         51
 2017-10-30       3         51
 2017-12-05       3         51

我试过这段代码,但它放了很多 NaN

group = df.groupby(by='customer_id')
df['diff'] = (group['action_date'].max() - group['action_date'].min()).dt.days

【问题讨论】:

    标签: python pandas group-by


    【解决方案1】:

    你可以使用transform方法:

    In [23]: df['diff'] = df.groupby('customer_id') \
                            ['action_date'] \
                            .transform(lambda x: (x.max()-x.min()).days)
    
    In [24]: df
    Out[24]:
      action_date  customer_id  diff
    0  2017-08-15            1    18
    1  2017-08-21            1    18
    2  2017-08-21            1    18
    3  2017-09-02            1    18
    4  2017-08-28            2    32
    5  2017-09-29            2    32
    6  2017-10-15            3    51
    7  2017-10-30            3    51
    8  2017-12-05            3    51
    

    【讨论】:

    • 谢谢!你太棒了:)
    • 如何在要减法的地方执行此操作,但在不同的列上,但使用最小和最大日期。 (比如说,你有一个叫做 customer_spend_amount 的东西,你想要基于日期减去第一个和最新的 customer_spend_amount)?
    • 如果我理解正确,类似这样的事情(基于 MaxU- 答案):df['diff'] = df.groupby('customer_id')['action_date'].transform(lambda x: (x - x.min()))
    猜你喜欢
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多