I am trying to add months and days based on conditions and I am hung up on DateOffsets passing in as a series. As you see below I used 0 as an index for date offsets, but this will give me the wrong answer.
I would prefer a vectorized solution if possible.
I am only using zero because I don't know how to access the internal row index enumeration of this np.select function. I am open to better ways to do this as well if this doesn't seem to be the best method.
This is similar to this question, but it doesn't outline how to do this with conditions. Add months to a date in Pandas
import pandas as pd
import numpy as np
# build dataframe
d = {
"order_type": ["New", "Renewal", "New"],
"ship_date": ["2011-01-15 00:00:00", "2011-01-10 00:00:00", "2011-01-10 00:00:00" ],
"expiring_date": ["2011-01-25 00:00:00", "2011-01-20 00:00:00", "2011-01-20 00:00:00"],
"contract_term": [12, 24, 36],
"grace_period": [45, 0, 30]}
df = pd.DataFrame(data=d)
# establish date conditions
conditions = [
((df["order_type"] == "New") & (df["grace_period"] == 0)), # 1
((df["order_type"] == "New") & (df["grace_period"] != 0)), # 2
df["order_type"] == "Renewal" # 3
]
choices = [
pd.to_datetime(df["ship_date"]) + pd.DateOffset(months=df["contract_term"].iloc[0]), # 1
pd.to_datetime(df["ship_date"]) + pd.DateOffset(months=df["contract_term"].iloc[0]) + pd.DateOffset(days=df["grace_period"].iloc[0]), # 2
df["expiring_date"] # 3
]
# return calculated end date
df["end_date"] = np.select(conditions, choices, default=pd.NaT)
# convert to datetime
df["end_date"] = pd.to_datetime(df["end_date"])
# print dataframe
df
Current incorrect output
index | order_type | ship_date | expiring_date | contract_term | grace_period | end_date |
---|---|---|---|---|---|---|
0 | New | 2011-01-15 00:00:00 | 2011-01-25 00:00:00 | 12 | 45 | 2012-02-29 |
1 | Renewal | 2011-01-10 00:00:00 | 2011-01-20 00:00:00 | 24 | 0 | 2011-01-20 |
2 | New | 2011-01-10 00:00:00 | 2011-01-20 00:00:00 | 36 | 30 | 2012-02-24 |
Expected Output
Notice when index = 2 the end_date is correctly calculated
index | order_type | ship_date | expiring_date | contract_term | grace_period | end_date |
---|---|---|---|---|---|---|
0 | New | 2011-01-15 00:00:00 | 2011-01-25 00:00:00 | 12 | 45 | 2012-02-29 |
1 | Renewal | 2011-01-10 00:00:00 | 2011-01-20 00:00:00 | 24 | 0 | 2011-01-20 |
2 | New | 2011-01-10 00:00:00 | 2011-01-20 00:00:00 | 36 | 30 | 2014-02-09 |