0

I have a DataFrame similar to the following, and I want to subtract the DateTimeIndex by numbers in the Day_Count column.

import pandas as pd

x = pd.DataFrame(np.arange(1,14), index = pd.date_range('2020-01-01', periods = 13, freq= 'D'), columns = ['Day_Count'])

                Day_Count
2020-01-01          1
2020-01-02          2
2020-01-03          3
2020-01-04          4
2020-01-05          5
2020-01-06          6
2020-01-07          7
2020-01-08          8
2020-01-09          9
2020-01-10         10
2020-01-11         11
2020-01-12         12
2020-01-13         13

So, the expected results should have the same DateTimeIndex of 2019-12-31 (e.g., 2020-01-01 minus one day, 2020-01-02 minus 2 days, and so on). I tried the following code but it does not work.

from dateutil.relativedelta import relativedelta
x.index = x.index - relativedelta(days = x.Day_Count)

Please help with this. Thank you in advance.

david78
  • 173
  • 11

1 Answers1

0

Try this code and see if it gives the expected result.

df.index = df.index - pd.to_timedelta(df['Day_Count'],unit='day')
rhug123
  • 7,893
  • 1
  • 9
  • 24