hk2
hk2

Reputation: 487

Assign Week Number beginning at 1 based on Dates starting in November

I have a date column with dates starting in the month of November. Below is a sample:

| dt         |
|------------|
| 11/13/2017 |
| 11/13/2017 |
| 11/13/2017 |
| 11/13/2017 |
| 11/20/2017 |
| 11/20/2017 |
| 11/27/2017 |
| 11/27/2017 |
| 11/27/2017 |
| 12/4/2017  |
| 12/11/2017 |
| 12/18/2017 |
| 12/18/2017 |
| 12/25/2017 |
| 1/1/2018   |
| 1/8/2018   |

I want to get week number from the dates but the week number should be 1 for 11/13/2017, 2 for 11/20/2017 and would continue to increase till 1/8/2018. How can I achieve this in Python?

Upvotes: 1

Views: 134

Answers (2)

BENY
BENY

Reputation: 323376

Let us do, PS just do not name your column as dt , since dt is a function from pandas

((df['dt']-df['dt'].min())//7).dt.days+1
Out[300]: 
0     1
1     1
2     1
3     1
4     2
5     2
6     3
7     3
8     3
9     4
10    5
11    6
12    6
13    7
14    8
15    9
Name: dt, dtype: int64

Upvotes: 2

Quang Hoang
Quang Hoang

Reputation: 150805

You can do:

df['week'] = (df['dt'] - df['dt'].min())//pd.to_timedelta('7D') + 1

Output:

           dt  week
0  2017-11-13     1
1  2017-11-13     1
2  2017-11-13     1
3  2017-11-13     1
4  2017-11-20     2
5  2017-11-20     2
6  2017-11-27     3
7  2017-11-27     3
8  2017-11-27     3
9  2017-12-04     4
10 2017-12-11     5
11 2017-12-18     6
12 2017-12-18     6
13 2017-12-25     7
14 2018-01-01     8
15 2018-01-08     9

Upvotes: 3

Related Questions