Transpose columns in python/pandas

13,478

You want to use the Period as an index. set_index will do this for you. Then you can transpose your resulting table:

df.set_index('Period').T
Out[13]: 
Period         2010         2011         2012
Name            foo          bar          nil
Value1  0,994369885   0,92930566  0,997754262
Value2  0,780942307  0,274566936  0,488064461
Value3  0,510782105  0,390724018  0,642086396
Value4  0,842522334  0,613705323  0,028703768
Value5  0,383279727  0,287280101  0,764773601
Share:
13,478
user2866103
Author by

user2866103

Updated on June 04, 2022

Comments

  • user2866103
    user2866103 almost 2 years

    I'm trying to rearrange a dataframe with 5 variables

    Data columns (total 7 columns):
    Nane      3966  non-null values
    Value1    3966  non-null values
    Value2    3966  non-null values
    Value3    3966  non-null values
    Value4    3966  non-null values
    Value5    3966  non-null values
    Period    3966  non-null values
    

    I'd like period to be the columns, and the other ones as rows.

    So

    Name Value1 .... Value 5 Period becomes
    
    Period 1 period 2 period3 .... period 3966   
    Name  
    Value 1  
    ...  
    Value 5
    

    I've tried using the stack/unstack and the transpose function, but I just can't figure it out. Does anyone have any pointers ?