Issue
I want to reshape my dataset from this:
Date | Item | A | B |
---|---|---|---|
1 | 1 | a1 | b1 |
1 | 2 | a2 | b2 |
1 | 3 | a3 | b3 |
to this
Date | Letter | Item 1 | Item 2 | Item 3 |
---|---|---|---|---|
1 | A | a1 | a2 | a3 |
1 | B | b1 | b2 | b3 |
I have tried using pd.pivot and pd.melt however I am unable to get the correct dataset.
Solution
df.pivot
result can be stacked with further reset_index(...)
:
out = (df.pivot(columns='Item', index='Date').stack(0)
.add_prefix('Item ').reset_index(names=['Date', 'Letter']))
Item Date Letter Item 1 Item 2 Item 3
0 1 A a1 a2 a3
1 1 B b1 b2 b3
Answered By - RomanPerekhrest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.