python pandas中融化的对面 [英] Opposite of melt in python pandas

查看:26
本文介绍了python pandas中融化的对面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在 python 中使用 Pandas 进行反向融化".这是我的起始数据

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

这是我想要的输出:

    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.

推荐答案

有几种方法;
使用 .pivot:

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]

使用 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]

.groupby 后跟 .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]

这篇关于python pandas中融化的对面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆