SosaAlmighty
SosaAlmighty

Reputation: 369

Python: Set days from a date as index for a plot

I have a data frame with dates as an index and I need to plot a graph with the index as x-axis. The problem is that I don't want the dates as index but the days from the first day. I hope I was clear enough. This is my dataframe:

             Open    High    Low
Date            
2012-10-15  632.35  635.13  623.85
2012-10-16  635.37  650.30  631.00
2012-10-17  648.87  652.79  644.00
2012-10-18  639.59  642.06  630.00
2012-10-19  631.05  631.77  609.62
... ... ... ...
2013-01-08  529.21  531.89  521.25
2013-01-09  522.50  525.01  515.99
2013-01-10  528.55  528.72  515.52
2013-01-11  521.00  525.32  519.02
2013-01-14  502.68  507.50  498.51

The final result should be like this:

enter image description here

Upvotes: 1

Views: 321

Answers (1)

Umar.H
Umar.H

Reputation: 23099

IIUC, we can take the min and do a simple sum whilst using np.timedelta to turn the DateTime into a days value.

import numpy as np

df['days'] = (df.index - df.index.min()) / np.timedelta64(1,'D')

print(df)

              Open    High     Low  days
Date                                    
2012-10-15  632.35  635.13  623.85   0.0
2012-10-16  635.37  650.30  631.00   1.0
2012-10-17  648.87  652.79  644.00   2.0
2012-10-18  639.59  642.06  630.00   3.0
2012-10-19  631.05  631.77  609.62   4.0
2013-01-08  529.21  531.89  521.25  85.0
2013-01-09  522.50  525.01  515.99  86.0
2013-01-10  528.55  528.72  515.52  87.0
2013-01-11  521.00  525.32  519.02  88.0
2013-01-14  502.68  507.50  498.51  91.0

Upvotes: 1

Related Questions