Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I create a future pandas datetime index based on a previous datetime index without specifying the frequency?

I have a pandas dataframe and it has a datetime index. I would like to take that index and create a new index that starts from one freq step after the last time and extends for n future steps. My problem is in creating the pd.DateOffset I need to specify the frequency, but I don’t want to hardcode that. Is there a way to determine the future index’s frequency from the original index? Here is my hardcoded example:

import pandas as pd
base_idx = pd.date_range('2022-10-05', '2022-10-12', name='times', freq='D')
print(base_idx)

DatetimeIndex(['2022-10-05', '2022-10-06', '2022-10-07', '2022-10-08',
               '2022-10-09', '2022-10-10', '2022-10-11', '2022-10-12'],
              dtype='datetime64[ns]', name='times', freq='D')


n = 5
future_idx = pd.date_range(base_idx.max() + pd.DateOffset(days=1), base_idx.max() + pd.DateOffset(days=5))
print(future_idx)
DatetimeIndex(['2022-10-13', '2022-10-14', '2022-10-15', '2022-10-16',
               '2022-10-17'],
              dtype='datetime64[ns]', freq='D')

I want to not have to state that it is in days because I might end up needing seconds, or weeks, etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can get the frequency from the base_idx index and use it to construct the new index:

future_idx = pd.date_range(
    base_idx.max() + base_idx.freq, base_idx.max() + n * base_idx.freq
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading