从数据框创建多索引

时间:2019-03-07 15:55:58

标签: python pandas

    Geography      Age group     2016
0  Toronto          All          1525
1  Toronto           1~7          5
2  Toronto           7~20          7
3  Toronto           20~40        500
4  Vancouver       All           3000
5  Vancouver       1~7            10
6  Vancouver       7~20          565
7  Vancouver       20~40         564
.
.
.

注意:这只是一个例子。我的数据框包含不同的数字

我想创建一个多索引,其中第一个索引是按地理位置划分的,第二个索引是按年龄段划分的。

还可以对分组进行分组,而最后不执行任何功能吗?

输出应为:

   Geography   Age group   2016
0  Toronto       All       1525
1                1~7         5
2                7~20        7
3                20~40      500
4  Vancouver     All       3000
5                1~7         10
6                7~20       565
7                20~40      564
.
.

1 个答案:

答案 0 :(得分:4)

要创建指定的MultiIndex,只需使用DataFrame.set_index()

df.set_index(['Geography','Agegroup' ])

                    2016
Geography Age group      
Toronto   All       1525
          1~7          5
          7~20         7
          20~40      500
Vancouver All       3000
          1~7         10
          7~20       565
          20~40      564