Search code examples
pythonpandasdataframeunpivot

pandas manipulate dataframe shape


I have a dataframe, df:

    x        hour     y
0   511746   08    53960
1   959377   11    85830

I wish to manipulate this to the form:

    type     hour  metric
0   x        08    511746
1   y        08    53960
2   x        11    959377
3   y        11    85830

How do I do this in pandas?


Solution

  • Use pd.melt() method:

    In [182]: pd.melt(df, id_vars='hour', value_vars=['x','y'], 
                      var_name='type', value_name='metric')
    Out[182]:
      hour type  metric
    0   08    x  511746
    1   11    x  959377
    2   08    y   53960
    3   11    y   85830