在Python Pandas中与melt相反的操作

107 投票
3 回答
73004 浏览
提问于 2025-04-17 20:30

我不知道怎么用Python里的Pandas库来实现“反熔化”。这是我现在的数据:

  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

我相信有简单的方法可以做到这一点,但我不知道怎么做。

3 个回答

0
 (
df.pivot(index="label",columns="type",values="value").
reset_index(level=0,drop=True)
)

另一种方法:

df.groupby(["label","type"])["value"].sum().unstack()

还有一种:

pd.crosstab(index=df.label, columns=df.type, values=df.value, aggfunc="su

8

DataFrame.set_index + DataFrame.unstack

df.set_index(['label','type'])['value'].unstack()

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

简化透视参数的传递

df.pivot(*df)

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

[*df]
#['label', 'type', 'value']

为了得到预期的结果,我们需要使用DataFrame.reset_indexDataFrame.rename_axis

df.pivot(*df).rename_axis(columns = None).reset_index()

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

如果a,b列中有重复值,我们可能会丢失一些信息,所以需要使用GroupBy.cumcount

print(df)

  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
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

df.pivot_table(index = ['label',
                        df.groupby(['label','type']).cumcount()],
               columns = 'type',
               values = 'value')


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

或者:

(df.assign(type_2 = df.groupby(['label','type']).cumcount())
   .set_index(['label','type','type_2'])['value']
   .unstack('type'))
138

有几种方法可以做到这一点:

第一种是使用 .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]

撰写回答