Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From RangeIndex to DatetimeIndex

Tags:

python

pandas

I am analyzing the time series of an action (historical from 2000 to 2018). I want to be able to better analyze my time series (e.g. on a monthly, quarterly basis) by placing all the datetime data in a DatetimeIndex. How can I do it? Is it possible?

df.columns
Out[181]: Index(['Date', 'Price', 'Open', 'High', 'Low'], dtype='object')

df.index
Out[179]: RangeIndex(start=0, stop=4309, step=1)

df.info
[4309 rows x 5 columns]>

type(df)
Out[178]: pandas.core.frame.DataFrame
like image 201
Napoleon Ricaurte Avatar asked Jan 27 '26 20:01

Napoleon Ricaurte


1 Answers

IIUC, you can just use:

df.set_index(pd.to_datetime(df['Date']))

Example:

>>> df
         Date  High  Low  Open  Price
0  1998-12-12     5   -1     3      1
1  2004-11-11     6   -2     4      2

df = df.set_index(pd.to_datetime(df['Date']))

>>> df
                  Date  High  Low  Open  Price
Date                                          
1998-12-12  1998-12-12     5   -1     3      1
2004-11-11  2004-11-11     6   -2     4      2
like image 153
sacuL Avatar answered Jan 30 '26 09:01

sacuL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!