Reputation: 27
I have a dataframe that looks like this with a lot of products
Product | Start Date |
---|---|
00001 | 2021/08/10 |
00002 | 2021/01/10 |
I want to make a cycle so that it goes from product to product subtracting three months from the date and then putting it in a variable, something like this. date[]=''
for dataframe in i:
date['3monthsbefore']=i['start date']-3 months
date['3monthsafter']=i['start date']+3 months
date['product']=i['product']
"Another process with those variables"
And then concat all this data in a dataframe I´m a little bit lost, I want to do this because I need to use those variables in another process, so I't is possible to do this?.
Upvotes: 0
Views: 40
Reputation: 5201
Using pandas, you usually don't need to loop over your DataFrame. In this case, you can get the 3 months before/after for all rows pretty simply using pd.DateOffset
:
df["Start Date"] = pd.to_datetime(df["Start Date"])
df["3monthsbefore"] = df["Start Date"] - pd.DateOffset(months=3)
df["3monthsafter"] = df["Start Date"] + pd.DateOffset(months=3)
This gives:
Product Start Date 3monthsbefore 3monthsafter
0 00001 2021-08-10 2021-05-10 2021-11-10
1 00002 2021-01-10 2020-10-10 2021-04-10
Data:
df = pd.DataFrame({"Product": ["00001", "00002"], "Start Date": ["2021/08/10", "2021/01/10"]})
Upvotes: 3