【问题标题】:Find date differences since inception within group查找组内自成立以来的日期差异
【发布时间】:2017-04-29 03:58:11
【问题描述】:

是否有一种有效的方法来计算表单中数据框的组内日期差异(以天为单位):

x = pd.DataFrame(
    {'grp':['A','A','A','B','B','B'],
     'dt':pd.DatetimeIndex(['1/1/00 00:00:00','1/2/00','1/3/00','1/2/01','1/3/01','1/5/01'])})
x
Out[1]: 
                   dt grp
0 2000-01-01 00:00:00   A
1 2000-01-02 00:00:00   A
2 2000-01-03 00:00:00   A
3 2001-01-02 00:00:00   B
4 2001-01-03 00:00:00   B
5 2001-01-05 00:00:00   B

这样结果类似于:

grp    days_since_start
A       0
A       1
A       2
B       0
B       1
B       3

【问题讨论】:

    标签: python python-3.x date group-by datediff


    【解决方案1】:

    当然。按组名分组,每组取时间最短,取差值:

    x.set_index('grp') - x.groupby('grp').min()
    #        dt
    #grp
    #A   0 days
    #A   1 days
    #A   2 days
    #B   0 days
    #B   1 days
    #B   3 days
    #Name: dt, dtype: timedelta64[ns]
    

    【讨论】:

    • 有趣的答案。我从来没有在非唯一列上设置索引()。但考虑到你的减法语句的两个术语有不同的长度,这里看起来很漂亮。就像您免费加入一样。
    • @MaxPower 在 Pandas 中称为数据对齐。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2015-09-03
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多