0

I'm trying to define a custom week for a dataframe.

I have a dataframe with timestamps. I've read the questions on here regarding isocalendar. While it does the job. It's not what I want.

I'm trying to define the weeks from Friday to Thrusday.

For example:

Friday 2nd Jan 2015 would be the first day of the week.

Thursday 8th Jan 2015 would be the last day of the week.

And this would be week 1.

Is there a way to set a custom weekday? so when I access the the datetime library, I get the result that I expect.

df['Week_Number'] = df['Date'].dt.week

Kvothe
  • 1,341
  • 7
  • 20
  • 33
  • Have a look at the timestamp offset documentation: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects. It may help! – dagrha Sep 07 '15 at 18:39
  • check this @Andy Hayden reply http://stackoverflow.com/questions/14530556/resample-time-series-in-pandas-to-a-weekly-interval/14531149#14531149 – Michal Sep 08 '15 at 09:06
  • @ Michal Thanks a lot. I'll check it out :) – Kvothe Sep 10 '15 at 10:06

1 Answers1

2

Here's one solution - convert your dates to a Period representing weeks that end on Thursday.

In [39]: df = pd.DataFrame({'Date':pd.date_range('2015-1-1', '2015-12-31')})

In [40]: df['Period'] = df['Date'].dt.to_period('W-THU')

In [41]: df['Week_Number'] = df['Period'].dt.week

In [44]: df.head()
Out[44]: 
        Date                Period  Week_Number
0 2015-01-01 2014-12-26/2015-01-01            1
1 2015-01-02 2015-01-02/2015-01-08            2
2 2015-01-03 2015-01-02/2015-01-08            2
3 2015-01-04 2015-01-02/2015-01-08            2
4 2015-01-05 2015-01-02/2015-01-08            2

Note that it follows the same convention as datetimes, where week 1 can be incomplete, so you may have to do a little extra munging if you want 1 to be the first complete week.

chrisb
  • 49,833
  • 8
  • 70
  • 70