xv70
xv70

Reputation: 982

Transform pandas timeseries into timeseries with non-date index

I'm trying to generate a timeseries from a dataframe, but the solutions I've found here don't really address my specific problem. I have a dataframe which is a series of id's which iterate from 1 to n, then repeat, like this:

   key                   ID           Var_1  
    0                 1            1
    0                 2            1
    0                 3            2
    1                 1            3
    1                 2            2
    1                 3            1

I want to reshape it into a timeseries in which the index

                  ID           Var_1_0       Var_2_0
                   1            1             3
                   2            1             2
                   3            2             1

I have tried the stack() method but it doesn't generate the result I want. Generating an index from ID seems to be the right ID is not a proper date so I'm not sure how to proceed. Pointers much appreciated.

Upvotes: 0

Views: 61

Answers (1)

Mamath
Mamath

Reputation: 307

Try this:

import pandas as pd
df = pd.DataFrame([[0,1,1], [0,2,1], [0,3,2], [1,1,3], [1,2,2], [1,3,1]], columns=('key', 'ID', 'Var_1'))

Use the pivot function:

df2 = df.pivot('ID', 'key', 'Var_1')

You can rename the columns by:

df2.columns = ('Var_1_0', 'Var_2_0')

Result:

Out: 
Var_1_0  Var_2_0
ID                  
1         1        3
2         1        2
3         2        1

Upvotes: 1

Related Questions