在pandas中创建周变量,并在一周内自定义开始日

时间:2017-09-04 22:24:54

标签: python python-3.x pandas

我将以下pandas数据帧索引到Time_Stamp:

df = DataFrame(index = pd.date_range('4/1/2017', freq='3D', periods=10))
df['weekday'] = df.index.weekday_name

数据如下所示:

              weekday
2017-04-01   Saturday
2017-04-04    Tuesday
2017-04-07     Friday
2017-04-10     Monday
2017-04-13   Thursday
2017-04-16     Sunday
2017-04-19  Wednesday
2017-04-22   Saturday
2017-04-25    Tuesday
2017-04-28     Friday

我想创建一个新专栏'周'这将是一年中的一周序数,但是有一个工作日。

我知道我可以这样做:

df['week_sun'] = df.index.week

除了我希望一周的第一天不是星期天。对于这个问题,让我说我需要它是星期三,以便产生的数据帧如下:

              weekday  week_sun  week_wed
2017-04-01   Saturday        13        13
2017-04-04    Tuesday        14        13
2017-04-07     Friday        14        14
2017-04-10     Monday        15        14
2017-04-13   Thursday        15        15
2017-04-16     Sunday        15        15
2017-04-19  Wednesday        16        16
2017-04-22   Saturday        16        16
2017-04-25    Tuesday        17        16
2017-04-28     Friday        17        17

我对如何实现这一点感到茫然。谢谢!

1 个答案:

答案 0 :(得分:1)

根据您的要求,您只需要将1减去周数,以防星期几在参考日“之前”(例如星期三)。

In [162]: df
Out[162]: 
              weekday  week_sun
2017-04-01   Saturday        13
2017-04-04    Tuesday        14
2017-04-07     Friday        14
2017-04-10     Monday        15
2017-04-13   Thursday        15
2017-04-16     Sunday        15
2017-04-19  Wednesday        16
2017-04-22   Saturday        16
2017-04-25    Tuesday        17
2017-04-28     Friday        17

In [163]: df['week_wed'] = df['week_sun']

现在让我们将值移到需要的位置,即工作日在星期三之前,因此df.index.dayofweek < 2

In [164]: df.loc[df.index.dayofweek < 2, 'week_wed'] = (df[df.index.dayofweek < 2]['week_sun'] - 2) % 52 + 1

In [165]: df
Out[165]: 
              weekday  week_sun  week_wed
2017-04-01   Saturday        13        13
2017-04-04    Tuesday        14        13
2017-04-07     Friday        14        14
2017-04-10     Monday        15        14
2017-04-13   Thursday        15        15
2017-04-16     Sunday        15        15
2017-04-19  Wednesday        16        16
2017-04-22   Saturday        16        16
2017-04-25    Tuesday        17        16
2017-04-28     Friday        17        17

我没有完全减去1,而是使用模运算((X-2) %52 +1))所以如果需要,我可以将第1周转换为第52周,如果需要:

              weekday  week_sun  week_wed
2017-12-27  Wednesday        52        52
2017-12-30   Saturday        52        52
2018-01-02    Tuesday         1        52
2018-01-05     Friday         1         1