Skip to content

Instantly share code, notes, and snippets.

@banditkings
Last active January 3, 2024 05:25
Show Gist options
  • Save banditkings/0518b56ffa4f37f7f5b85bc0b920be6c to your computer and use it in GitHub Desktop.
Save banditkings/0518b56ffa4f37f7f5b85bc0b920be6c to your computer and use it in GitHub Desktop.
Create a week of year feature from a pandas datetime column
import pandas as pd
def create_week_feature(df:pd.DataFrame, date_col='DateTime'):
"""
Given a dataframe with a column `date_col` of type pd.DateTime
"""
if type(df[date_col]) != pd.DateTime:
df[date_col] = pd.to_datetime(df[date_col])
# Use the pd.Series.dt.isocalendar() method to access
# additional features, like the week in year
weeks = df[date_col].dt.isocalendar().week
# add in an indicator column `Is_Week` + the week number,
# i.e. `Is_Week52`
df.loc[:, 'WeekInYear'] = ['Is_Week'+str(i) for i in weeks]
# dummify the features
week_features = pd.get_dummies(df['WeekInYear'], dtype=int)
df = pd.concat([df, week_features], axis=1)
return df
@banditkings
Copy link
Author

When dealing with the pandas pd.DateTime type we sometimes need to get a week feature that specifies the week in the calendar year. The easiest way to do this is to use the pd.Series.dt.isocalendar() method and then it unlocks the .week attribute on the date.

If you're dealing with a fiscal calendar then you'll need to do something different.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment