Search code examples
pythonpandasdate-range

How to create a custom frequency in pandasper day at 9, 12 and 18 o'clock


I understand how to create a pandas frequency like in python3:

import pandas as pd 

import datetime

idx = pd.date_range('2017-01-01' ,'2017-06-16',  freq='D')

ts = pd.Series(range(len(idx)), index=idx)

ts

How would I do this for irregularly sampled hourly data of 9 12 and 18 o'clock?


Solution

  • You can try:

    idx = pd.date_range('2017-01-01' ,'2017-06-16',  freq='H')
    idx = idx[idx.hour.isin([9,12,18])]
    
    ts = pd.Series(range(len(idx)), index=idx)
    

    Output:

    2017-01-01 09:00:00      0
    2017-01-01 12:00:00      1
    2017-01-01 18:00:00      2
    2017-01-02 09:00:00      3
    2017-01-02 12:00:00      4
                          ... 
    2017-06-14 12:00:00    493
    2017-06-14 18:00:00    494
    2017-06-15 09:00:00    495
    2017-06-15 12:00:00    496
    2017-06-15 18:00:00    497
    Length: 498, dtype: int64