python - python pandas中融化的对面

标签 python pandas pivot reshape melt

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

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

我确信有一种简单的方法可以做到这一点,但我不知道如何。

最佳答案

有几种方法;
使用 .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 - python pandas中融化的对面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22127569/

相关文章:

python - 在 python 中使用 count()

python - 对非常大的 Pandas Data frame 进行聚合和统计

python - 如何根据另一个数据帧计算一个数据帧中的类别?

python - 具有不等列的 Pandas 透视数据框

python - Py_Main() 似乎是一个 NOOP

python - 如何对每列中的所有值求和并将每列除以求和值

python - 总结 Python Pandas 中两列(双向)的组合计数

sql - 将多行合并为多列

python - 在现有 DataFrame 中设置 DateTimeIndex

python解析: what file format uses `=>` OR how to read custom input files to dict