pandas 使用数据框索引数据的熊猫数据透视表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21646710/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas pivot table using index data of dataframe
提问by user3276418
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?
我想使用 dataframe.pivot() 从 Pandas 数据帧创建一个数据透视表,不仅包括数据帧列,还包括数据帧索引中的数据。找不到任何说明如何执行此操作的文档。有小费吗?
回答by unutbu
Use reset_indexto make the index a column:
使用reset_index使索引中的列:
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:
因此,pivot 使用索引作为值:
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    

