How do I create a future pandas datetime index based on a previous datetime index without specifying the frequency?
Question:
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.
Answers:
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
)
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.
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
)