DKM
DKM

Reputation: 1801

Pandas Append Week Column In dataframe using dates

I have a data frame available with date column like below.

df = pd.DataFrame({'Date':pd.date_range('2018-10-01', periods=14)})

enter image description here

I want to append week number column based on date, so it will look like

enter image description here

so the 2018-10-01 will be week 1 and after 7 days 2018-10-08 would be week 2 and so on.

Any help how can I perform this?

Upvotes: 1

Views: 530

Answers (1)

jezrael
jezrael

Reputation: 862541

Use weekday with factorize with add 1 for groups starting from 1:

df['Week'] = pd.factorize(df['Date'].dt.weekofyear)[0] + 1
print (df)
         Date  Week
0  2018-10-01     1
1  2018-10-02     1
2  2018-10-03     1
3  2018-10-04     1
4  2018-10-05     1
5  2018-10-06     1
6  2018-10-07     1
7  2018-10-08     2
8  2018-10-09     2
9  2018-10-10     2
10 2018-10-11     2
11 2018-10-12     2
12 2018-10-13     2
13 2018-10-14     2

Upvotes: 4

Related Questions