pandasdatestamp

indexing by windows with step gap over a pandas DF


My df is datestamp index. I need to split it in two different df with fixed window (for exemple 2 day) in alternation like this:

enter image description here

df1 = yellow ans df2 the white

Thank so much for your help


Solution

  • Assuming the following example input:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'date': pd.date_range('2021-01-01', '2021-01-14'),
                       'value': np.random.randint(0, 100, size=14)
                      })
    

    If you have a range index, you could use it to compute a group and split:

    out = dict(list(df.groupby(df.index//2%2)))
    

    output:

    >>> out[0]
             date  value
    0  2021-01-01      5
    1  2021-01-02     35
    4  2021-01-05     25
    5  2021-01-06     59
    8  2021-01-09     32
    9  2021-01-10     44
    12 2021-01-13     22
    13 2021-01-14      6
    
    >>> out[1]
             date  value
    2  2021-01-03     36
    3  2021-01-04     97
    6  2021-01-07     10
    7  2021-01-08     57
    10 2021-01-11     31
    11 2021-01-12     28