I have a dataset where I would like to shift the month and years in a given column based on an integer value. a2 column is effected when we input the integer: 9
We are incrementing the month by the value 9. We start with month 4 and add 9 more months = 1/1/2023
Data
start a1 a2 stat exit
1/1/2018 1/1/2022 4/1/2022 5/1/2022 6/1/2022
1/1/2018 1/1/2022 4/1/2022 5/1/2022 6/1/2022
1/1/2018 1/1/2022 4/1/2022 5/1/2022 6/1/2022
Desired output
start a1 a2 stat exit
1/1/2018 1/1/2022 1/1/2023 5/1/2022 6/1/2022
1/1/2018 1/1/2022 1/1/2023 5/1/2022 6/1/2022
1/1/2018 1/1/2022 1/1/2023 5/1/2022 6/1/2022
Doing
d = {
'm1': pd.DateOffset(months=3),
'de': pd.DateOffset(months=5),
're': pd.DateOffset(months=2),
}
s = pd.Series(d).rsub(datevalue)
monthvalue = pd.to_datetime(input("Enter month value: ")) #enter 9
new = pd.Series(d).rsub(datevalue) \
.append(pd.Series({'a2': monthvalue}))
I am still researching this. Any suggestions is helpful. I am not sure if we can mix datetime w./ integer input.
CodePudding user response:
Use pd.to_datetime with pd.DateOffset:
# Convert all columns to pandas datetime
In [558]: df = pd.DataFrame([pd.to_datetime(df[i]) for i in df.columns]).T
# Take user input for monthvalue
In [559]: monthvalue = int(input("Enter month value: "))
Enter month value: 9
# If monthvalue entered by user is 9, then add 9 months to column 'a2'
In [560]: if monthvalue == 9:
...: df['a2'] = df['a2'] pd.DateOffset(months=monthvalue)
...:
In [561]: df
Out[561]:
start a1 a2 stat exit
0 2018-01-01 2022-01-01 2023-01-01 2022-05-01 2022-06-01
1 2018-01-01 2022-01-01 2023-01-01 2022-05-01 2022-06-01
2 2018-01-01 2022-01-01 2023-01-01 2022-05-01 2022-06-01
