Mr_12
Mr_12

Reputation: 23

Finding the weeks of each year separately in python

all. Could you please help me print the week of each year separately? I try to find the week of years by the help of visit['week_start']=visit['start_ts'].dt.week code . But it mixes of all years and prints as one the same week. For example, 2017.01.01 and 2018.01.01 are 0 weak. But I want to print them separately such as 2017 0 weeks and 2018 0 weeks. Thanks in advance.

start_ts is here

enter image description here

week_start is here

enter image description here

Upvotes: 1

Views: 132

Answers (2)

accumulate the years in a list then use the date_range for each year to find the weeks in that year and use as a mask

index= pd.date_range(start='2021-1-1',periods=52,freq='W')
print(index)

Upvotes: 0

Guillaume Ansanay-Alex
Guillaume Ansanay-Alex

Reputation: 1252

df['week_start'] = df.start_ts.dt.isocalendar()['year'].astype(str) + \
                   ' ' + df.start_ts.dt.isocalendar()['week'].astype(str)

Upvotes: 1

Related Questions