Search code examples
pythonpandasgrouped-bar-chart

Transforming dataframe before plotting


I want to create a horizontal bar chart, however I think I would have to use the pivot method first. The current dataframe consists of two rows and many columns:

    Names       not_needed     not_needed2         year1         year2         year3
    Joe         0              0                   240.87        2.30          0.85
    Doe         0              0                   243.72        2.35          0.84

To plot this into a bar chart I would like to first transform the data into this:

    Years       Joe        Doe   
    year1       240.87     243.72    
    year2       2.30       2.35  
    year3       .85        .84 

This way I can have two horizontal bar charts stacked on top of each other where the y axis labels the years and the x axis labels the data numbers.


Solution

  • Just a simple transpose will do actually. No need for a pivot.

    df1 = df.set_index('Names')[['year1','year2','year3']].T
    
    print(df1)
    
              Joe     Doe
    year1  240.87  243.72
    year2    2.30    2.35
    year3    0.85    0.84