Reputation: 19
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.
Upvotes: 0
Views: 39
Reputation: 150735
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
Upvotes: 2