Search code examples
pythonunpivot

how to un-pivot multi-column data?


I am trying to Unpivot columns and get 1 attributes and 2 value from a pandas dataframe, could anyone help me on this?

original data:

 id Jan-Value1 Jan-Value2 Feb-Value1 Feb-Value2
 1  1          10         2          15
 2  0          5          3          20

desire output:

 id Month Value1 Value2
 1  Jan   1      10
 1  Feb   2      15
 2  Jan   0      5
 2  Feb   3      20 

Solution

  • One possible way to do this is to use MultiIndex and stack. For this solution, I am assuming that id is the index of the dataframe:

    #df.set_index('id',inplace=True)  #set 'id' as index
    
    #creating a Multiindex using existing columns 
    df.columns = df.columns.str.split('-', expand=True).swaplevel(0,1)
    
    #stacking the dataframe
    df = df.stack().reset_index()
    
    #renaming the column 
    df.rename(columns={'level_1':'Month'},inplace=True)
    print(df)
    

    Output:

       id Month  Value1  Value2
    0   1   Feb       2      15
    1   1   Jan       1      10
    2   2   Feb       3      20
    3   2   Jan       0       5