简体   繁体   中英

How to change column values to rows value based on condition

df:

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

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

I need to change the Column Values to Row Values as in the example. I tried some stack() function but it didn't worked.

You are looking to combine stack and unstack :

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

Output:

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM