Replace Pandas Dataframe Values with Date

Viewed 370

I have a time series dataframe with dates as index and days to maturity "DTM" values. What is the best way to replace these DTM values with actual dates (adding the existing value to the date index row date)?

enter image description here

For example: Adding 20 days to 1990-01-02 = 1990-01-22 for the first row/first column value.

thanks!

1 Answers

Creating similar dataframe to the one you posted:

import pandas as pd
array = {'Date': ['1990-01-02', '1990-01-03'],
         'CL1': [20,19],
         'CL2': [49,48], 'CL3': [77,76]}
df = pd.DataFrame(array)
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
df = df.set_index('Date')
df

This gives:

           CL1  CL2 CL3
Date            
1990-01-02  20  49  77
1990-01-03  19  48  76

Now here is the solution to what you are after:

from datetime import timedelta
for col in df.columns:
    df[col] = df.index + pd.to_timedelta(df[col], unit='d') 
df

Which gives:

                CL1          CL2       CL3
Date            
1990-01-02  1990-01-22  1990-02-20  1990-03-20
1990-01-03  1990-01-22  1990-02-20  1990-03-20
Related