Skip to content Skip to sidebar Skip to footer

Creating Year Week Based On Date With Different Start Date

I have a df date 2021-03-12 2021-03-17 ... 2022-05-21 2022-08-17 I am trying to add a column year_week, but my year week starts at 2021-06-28, which is the first day of July. I t

Solution 1:

Here is a way, I added two dates more than a year away. You need the isocalendar from the difference between the date column and the dayofyear of your specific date. Then you can select the different scenario depending on the year of your specific date. use np.select for the different result format.

#dummy dataframe
df = pd.DataFrame(
    {'date': ['2020-03-12',  '2021-03-12',  '2021-03-17', '2021-06-28',  
              '2022-05-21', '2022-08-17', '2023-08-17']
    }
)

# define start date
d = pd.to_datetime('2021-6-24')

# remove the nomber of day of year from each date
s = (pd.to_datetime(df['date']) - pd.Timedelta(days=d.day_of_year)
    ).dt.isocalendar()

# get the difference in year
m = (s['year'].astype('int32') - d.year)

# all condition of result depending on year difference
conds = [m.eq(0), m.eq(-1), m.eq(1), m.lt(-1), m.gt(1)]
choices =  ['', 'LY','NY',(m+1).astype(str)+'LY', '+'+(m-1).astype(str)+'NY']

# create the column
df['res'] = np.select(conds, choices) + s['week'].astype(str)

print(df)
         date     res
0  2020-03-12  -1LY38
1  2021-03-12    LY38
2  2021-03-17    LY39
3  2021-06-28       1
4  2022-05-21      47
5  2022-08-17     NY8
6  2023-08-17   +1NY8

Solution 2:


Post a Comment for "Creating Year Week Based On Date With Different Start Date"