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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.