I have a pandas dataframe with two id variables:
df = pd.DataFrame({'id': [1,1,1,2,2,3], 'num': [10,10,12,13,14,15], 'q': ['a', 'b', 'd', 'a', 'b', 'z'], 'v': [2,4,6,8,10,12]}) id num qv 0 1 10 a 2 1 1 10 b 4 2 1 12 d 6 3 2 13 a 8 4 2 14 b 10 5 3 15 z 12
I can expand the table with:
df.pivot('id','q','v')
And it turned out something close:
qabdz id 1 2 4 6 NaN 2 8 10 NaN NaN 3 NaN NaN NaN 12
However, I really want (original unmelted form):
id num abdz 1 10 2 4 NaN NaN 1 12 NaN NaN 6 NaN 2 13 8 NaN NaN NaN 2 14 NaN 10 NaN NaN 3 15 NaN NaN NaN 12
In other words:
- 'id' and 'num' are my indexes (usually I only saw "id" or "num" being an index, but I need both since I'm trying to restore the original unmelted form)
- 'q' are my columns
- 'v' are my values ββin the table
Update
I found a solution to close from Wes McKinney 's blog :
df.pivot_table(index=['id','num'], columns='q') vqabdz id num 1 10 2 4 NaN NaN 12 NaN NaN 6 NaN 2 13 8 NaN NaN NaN 14 NaN 10 NaN NaN 3 15 NaN NaN NaN 12
However, the format is not quite the same as above.