neosday
neosday

Reputation: 25

Get Week number from date time python pandas data frame(starting Sunday)

Hi I am working with a time series data frame (data) which looks something like this: image

  date          count
1 2017-01-01    198.50
2 2017-01-01    338.00

So when I try to make a week_number column(week starting from Sunday) using this:

data['Week_Number'] = data['most_recent_order_date'].dt.week

I basically get:

date            count        Week_Number
2017-01-01      198.50       52
2017-01-01      338.00       52
2017-01-01      508.00       52
2017-01-02      98.50        1

So can anyone please help in fixing this?

Thanks for your help in advance.

Upvotes: 0

Views: 233

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34056

You can do something like this:

In [128]: df
Out[128]: 
        date    val
0 2017-01-01  198.5
1 2017-01-01  338.5
2 2017-01-02   98.5

In [319]: df['date'] = pd.to_datetime(df['date'])
In [323]: df['Week_Number'] = df['date'].dt.strftime('%U') 

In [324]: df 
Out[324]: 
        date    val Week_Number
0 2017-01-01  198.5          01
1 2017-01-01  338.5          01
2 2017-01-02   98.5          01

So, basically, strftime("%U") returns the week_number starting from Sunday. You can read more from : http://strftime.org/

Upvotes: 1

Related Questions