重命名pandas数据透视表而不会丢失轴标签

时间:2013-01-16 16:05:27

标签: python pandas pivot-table

当我在数据透视表上调用重命名时,我丢失了轴标签:

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

有没有办法在不丢失轴标签的情况下执行此操作?

1 个答案:

答案 0 :(得分:1)

当你转动时,x和y 的值是标签,这是预期的行为。

试试这个:

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