ChrisB
ChrisB

Reputation: 4718

Renaming a pandas pivot table without losing axis labels

When I invoke rename on a pivot table, I lose the axis labels:

In [5]: df = pd.DataFrame(dict(x=[0,0,1,0,1], y=[1,0,1,1,0], z=[0,0,1,0,1]))
In [6]: pt = pd.pivot_table(df, 'z', cols='x', rows='y')
In [7]: print pt
x  0  1
y      
0  0  1
1  0  1
In [8]: labels = {0:'False', 1:'True'}
In [9]: print pt.rename(index=labels, columns=labels) # discards "x" and "y"
       False  True
False      0     1
True       0     1

Is there a way to do this without losing the axis labels?

Upvotes: 0

Views: 1715

Answers (1)

guyrt
guyrt

Reputation: 927

When you pivot, the values of x and y are the labels, and that is expected behaviour.

Try this:

df['x'] = df['x'] == 1
pt = pandas.pivot_table(df, 'z', cols='x', rows='y')
print pt
x  False  True 
y               
0      0      1
1      0      1

Upvotes: 1

Related Questions