代码之家  ›  专栏  ›  技术社区  ›  Cranjis

大熊猫从一个单独的日期列表中的相应日期获得delta

  •  1
  • Cranjis  · 技术社区  · 2 年前

    df a b
       7 2019-05-01 00:00:01
       6 2019-05-02 00:15:01 
       1 2019-05-06 00:10:01
       3 2019-05-09 01:00:01
       8 2019-05-09 04:20:01
       9 2019-05-12 01:10:01
       4 2019-05-16 03:30:01
    

    l = [datetime.datetime(2019,05,02), datetime.datetime(2019,05,10), datetime.datetime(2019,05,22) ]

    我想添加一列,其中包含以下内容: 对于每一行,从l中找到它之前的最后一个日期,并加上它们之间的天数。 如果没有一个日期更小,则从最小的日期加上增量。 因此,新列将是:

    df a b.                 delta
       7 2019-05-01 00:00:01 -1
       6 2019-05-02 00:15:01  0
       1 2019-05-06 00:10:01  4
       3 2019-05-09 01:00:01  7
       8 2019-05-09 04:20:01  7
       9 2019-05-12 01:10:01  2
       4 2019-05-16 03:30:01  6
    

    1 回复  |  直到 2 年前
        1
  •  1
  •   mozway    2 年前

    使用 merge_asof 对齐的步骤 df['b']

    # ensure datetime
    df['b'] = pd.to_datetime(df['b'])
    
    # craft Series for merging (could be combined with line below)
    s = pd.Series(l, name='l')
    
    # merge and fillna with minimum date
    ref = pd.merge_asof(df['b'], s, left_on='b', right_on='l')['l'].fillna(s.min())
    
    # compute the delta as days
    df['delta'] =(df['b']-ref).dt.days
    

    输出:

       a                   b  delta
    0  7 2019-05-01 00:00:01     -1
    1  6 2019-05-02 00:15:01      0
    2  1 2019-05-06 00:10:01      4
    3  3 2019-05-09 01:00:01      7
    4  8 2019-05-09 04:20:01      7
    5  9 2019-05-12 01:10:01      2
    6  4 2019-05-16 03:30:01      6
    
        2
  •  0
  •   ArrowRise    2 年前

    这是一个单行解决方案,如果你 b datetime 对象否则将其转换为 日期时间 对象

    df['delta'] = df.apply(lambda x: sorted([x.b - i for i in l], key= lambda y: y.seconds)[0].days, axis=1) 
    

    • 计算 deltatime 在你的排之间 日期时间 而且每 出现在 l ,然后将其存储在列表中
    • deltatime公司
    • 获取第一个值(最小值 deltatime公司 )并返回其 days
        3
  •  0
  •   shubham koli    2 年前

    • 周工作日 星期五
    • 2014
    • 白天 01
    • 00
    rides['weekday'] = rides.timestamp.dt.strftime("%A")
    rides['year'] = rides.timestamp.dt.strftime("%Y")
    rides['day'] = rides.timestamp.dt.strftime("%d")
    rides['hour'] = rides.timestamp.dt.strftime("%H")
    rides["minute"] = rides.timestamp.dt.strftime("%M")