Search code examples
pythonsktime

Shift/ change the index of a dataframe


I am preparing a dataset in the "pd-multiindex" format for usage in a library called sktime. It looks like the following.

instances time points a b      
0         0            2 -2
          1            1 -1
          2            1 -2
          3           -2  2
          4           -2  2
...                   .. ..
826       9           -1  1
          10          -1  0
          11           1  0
          12          -1  1
          13           2 -2

The "instances" and "time points" form a multi-index. I would like to change the starting index of instances from 0 to 826 (and so the ending index would become 826+826=1652)


Solution

  • Try this code once

     import pandas as pd
    
    # assuming your DataFrame with a MultiIndex
    
    print("Before:", df.index.get_level_values(0).unique())
    
    # Update the MultiIndex: add 826 to the first level 
    df.index = df.index.map(lambda idx: (idx[0] + 826, idx[1]))
    
    # Check the final answer
    print("After:", df.index.get_level_values(0).unique())