I have a pandas dataframe with one of the columns being a date. I need to create another column which would be a start (or end, doesn't matter) of a 2W period containing this date. Ideally this would be generalizable to any offset used by pd.Grouper.
Knowing pd.Grouper I can come up with a hacky solution using .groupby.transform() - but I hope there is a nicer solution.
I tried using pd.Series.dt.to_period() but it does not accept offsets like "2W" and interprets them as a weekly offset. I could not find documentation of dt.to_period() that would explain this.
df = pd.DataFrame({"date":["2022-01-03", "2022-01-10", "2022-01-20"], "data":[1,2,3]})
df["date"] = pd.to_datetime(df["date"])
# Trying to assign a 2W period to a new column
# This is ugly and hacky, and pd.Grouper is deprecated
# can this be made better?
df["2W_date_grouper"] = df.groupby(pd.Grouper(freq="2W", key="date"))["data"].transform(lambda x:[x.name]*len(x))
# using .dt.to_period() seems to ignore "2W" and interpret it as "weekly" - WHY???
df["2W_date_to_period"] = df["date"].dt.to_period("2W")
