Opposite of melt in python pandas

前端 未结 2 1671
心在旅途
心在旅途 2020-11-30 19:58

I cannot figure out how to do \"reverse melt\" using Pandas in python. This is my starting data

import pandas as pd

from StringIO import StringIO

origin =          


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 20:34

    there are a few ways;
    using .pivot:

    >>> origin.pivot(index='label', columns='type')['value']
    type   a  b  c
    label         
    x      1  2  3
    y      4  5  6
    z      7  8  9
    
    [3 rows x 3 columns]
    

    using pivot_table:

    >>> origin.pivot_table(values='value', index='label', columns='type')
           value      
    type       a  b  c
    label             
    x          1  2  3
    y          4  5  6
    z          7  8  9
    
    [3 rows x 3 columns]
    

    or .groupby followed by .unstack:

    >>> origin.groupby(['label', 'type'])['value'].aggregate('mean').unstack()
    type   a  b  c
    label         
    x      1  2  3
    y      4  5  6
    z      7  8  9
    
    [3 rows x 3 columns]
    

提交回复
热议问题