I want to create a pivot table from a pandas dataframe using dataframe.pivot() and include not only dataframe columns but also the data within the dataframe index. Couldn't find any docs that show how to do that. Any tips?
Asked
Active
Viewed 1.7k times
10
-
Have you tried anything? Please at least provide a minimal example to work with. – Xiphias Feb 08 '14 at 13:43
1 Answers
16
Use reset_index
to make the index a column:
In [45]: df = pd.DataFrame({'y': [0, 1, 2, 3, 4, 4], 'x': [1, 2, 2, 3, 1, 3]}, index=np.arange(6)*10)
In [46]: df
Out[46]:
x y
0 1 0
10 2 1
20 2 2
30 3 3
40 1 4
50 3 4
In [47]: df.reset_index()
Out[47]:
index x y
0 0 1 0
1 10 2 1
2 20 2 2
3 30 3 3
4 40 1 4
5 50 3 4
So pivot uses the index as values:
In [48]: df.reset_index().pivot(index='y', columns='x')
Out[48]:
index
x 1 2 3
y
0 0 NaN NaN
1 NaN 10 NaN
2 NaN 20 NaN
3 NaN NaN 30
4 40 NaN 50

unutbu
- 842,883
- 184
- 1,785
- 1,677