使用dataframe索引数据的pandas数据透视表 [英] pandas pivot table using index data of dataframe

查看:324
本文介绍了使用dataframe索引数据的pandas数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从pandas数据框创建数据透视表 使用dataframe.pivot() 并且不仅包括数据框列,还包括数据框索引中的数据. 找不到任何显示该操作方法的文档. 有提示吗?

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?

推荐答案

使用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

因此,pivot将索引用作值:

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    

这篇关于使用dataframe索引数据的pandas数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆