简体   繁体   English

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

[英]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? 有没有办法做到这一点而又不会丢失轴标签?

When you pivot, the values of x and y are the labels, and that is expected behaviour. 旋转时,x和y的值标签,这是预期的行为。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM