首页 > 解决方案 > 如何根据条件将列值更改为行值

问题描述

东风:

items    M1     v1     v2     v3 
A        c1     56     52     25
A        c2     66     63     85
B        c1     29     76     36
B        c2     14     24     63

df_输出:

items   M1    C1    C2
  A     V1    56    66
  A     V2    52    63
  A     V3    25    85
  B     V1    29    14
  B     V2    76    24
  B     V3    36    60

我需要将列值更改为行值,如示例中所示。我尝试了一些 stack() 函数,但没有奏效。

标签: pythonpandas

解决方案


您正在寻找结合stackunstack

(df.set_index(['items','M1'])
   .unstack('M1')                             # unstack promotes M1 to columns
   .stack(level=0)                            # stack turns original columns to index level
   .rename_axis(columns=None, index=['item','M1'])  # rename to match output
   .reset_index()
)

输出:

  item  M1  c1  c2
0    A  v1  56  66
1    A  v2  52  63
2    A  v3  25  85
3    B  v1  29  14
4    B  v2  76  24
5    B  v3  36  63

推荐阅读