11

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?

1
  • Have you tried anything? Please at least provide a minimal example to work with. Commented Feb 8, 2014 at 13:43

1 Answer 1

17

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    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.