【问题标题】:Extracting the week from python datetime and getting the serial number?从python datetime中提取星期并获取序列号?
【发布时间】:2019-12-24 03:59:53
【问题描述】:

我有一个数据框,其列名 order date 包含从 2014 年 7 月到 2015 年 6 月的日期,格式为 2014-10-17 15:11:54。使用 datetime 我从日期中提取了周数。但是,我将 2014 年 7 月的起始周设为 27,而不是 2015 年 1 月的起始周从第 1 周开始。我想要的是 2014 年 7 月,因为第 1 周持续到 2015 年 6 月并以 53 结束。

df['Week'] = df.order_date.dt.week 

使用上面的代码获取之后的周数,以获取 2014 年 7 月使用的 1

def time_period(x):
    if df.Week >= 26:
        return df.Week -25
    else:
        return df.Week +28
df['week_serial'] = df.Week.apply(lambda x: time_period(x))

这给出了一个错误 - Series 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

    标签: python python-3.x pandas datetime


    【解决方案1】:

    鉴于您已经拥有 datetime.datetime 对象,使用这些对象可能是最简单的。

    首先,定义你的开始日期。

    In [1]: import datetime
    
    In [2]: start  = datetime.datetime(2014, 7, 1)
    Out[2]: datetime.datetime(2014, 7, 1, 0, 0)
    

    然后确定每个日期和开始之间的timedelta,并将其转换为天和周。

    In [3]: (datetime.datetime(2015, 3, 24) - start).days
    Out[3]: 266
    
    In [4]: (datetime.datetime(2015, 3, 24) - start).days // 7 + 1
    Out[4]: 39
    

    【讨论】:

      【解决方案2】:

      既然df.Week 已经包含周数,函数应该如下所示:

      def time_period(x):
          if x >= 26:
              return x-25
          else:
              return x+28

      但我认为您在这里基本上是在寻找模运算:

      df['week_serial'] = (df['Week'] + 27) <b>% 53</b> + 1

      这会将26映射到127映射到2等;以及53 上的2552 上的24,等等。

      所以对于样本输入:

      >>> df
         Week
      0    13
      1    49
      2    47
      3    12
      4    35
      5    17
      6     1
      7    46
      8    19
      9     0
      

      我们得到:

      >>> (df['Week'] + 27) % 53 + 1
      0    41
      1    24
      2    22
      3    40
      4    10
      5    45
      6    29
      7    21
      8    47
      9    28
      Name: Week, dtype: int64
      

      【讨论】:

      • 它有效,但应该是 +26 而不是 +27 @Willem Van Onsem
      • @NadeemHaque:但原来的问题并不完全正确。 (df['Week'] + 27) % 53 + 1 与您提供的 def time_period(x): “和谐”。那么这个函数可能并不完全正确?
      • time_period(x) 是从 26 开始
      • @NadeemHaque:是的,确实如此,但我们使用额外的 +1 来补偿模环绕。
      • 是的,但是 +1 加起来就是下周,结果是 2 而不是 1
      猜你喜欢
      • 2015-03-16
      • 2022-07-23
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      • 2019-09-22
      • 2020-01-02
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多