Opposite of melt in python pandas

拈花ヽ惹草 提交于 2019-11-26 15:19:25

问题


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 = pd.read_table(StringIO('''label    type    value
x   a   1
x   b   2
x   c   3
y   a   4
y   b   5
y   c   6
z   a   7
z   b   8
z   c   9'''))

origin
Out[5]: 
  label type  value
0     x    a      1
1     x    b      2
2     x    c      3
3     y    a      4
4     y    b      5
5     y    c      6
6     z    a      7
7     z    b      8
8     z    c      9

This is the output I would like to have:

    label   a   b   c
        x   1   2   3
        y   4   5   6
        z   7   8   9

I'm sure there is an easy way to do this, but I don't know how.


回答1:


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]


来源:https://stackoverflow.com/questions/22127569/opposite-of-melt-in-python-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!