2

I need to partition pandas.tslib.Timestamp into weeks. So, given that a is a pd.DataFrame I used

tmp = pd.to_datetime(a) 
tmp = tmp.apply(lambda x: str(str(x.isocalendar()[1]))

The problem is that my week starts not on Monday or Sunday but Tuesday (it can even start on Wed - it is user defined). Is it possible to change the starting week definition and still to use generic python functions?

Or is there another work-around?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user3861925
  • 713
  • 2
  • 10
  • 24

1 Answers1

3

Use an offset; you can re-cast the weekday value to any other in the range, then subtract from the week number:

user_sow = 3  # wednesday (monday is 1, sunday is 7)

tmp.apply(lambda x: x.isocalendar()[1] - (x.isoweekday() < user_sow))

This subtracts 1 (boolean True is equal to 1 in integer contexts) from the week number if the weekday is before the start of the user-configured week.

Demo:

>>> dt = date.today()   # today's a Wednesday
>>> dt
datetime.date(2015, 4, 28)
>>> dt.isocalendar()[1]
18
>>> dt.isocalendar()[1] - (dt.isoweekday() < 2)  # week starts on Tuesday
18
>>> dt.isocalendar()[1] - (dt.isoweekday() < 3)  # week starts on Wednesday
17
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • From what I understood dt.isocalendar()[1] has some bugs (Feb 29 goes to 'The next year' and suchlike). strftime("%U"), on the other hand does not work on Feb-29 at all (I tried and it works for Feb-28 given in the same format..) Do you have a better suggestion for finding week? Sorry for bugging and thank you. – user3861925 Apr 28 '15 at 11:45