简体   繁体   English

从数据框创建多索引

[英]creating multi-index from dataframe

    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
.
.
.

NOTE: This is just an example. 注意:这仅是示例。 my dataframe contains different numbers 我的数据框包含不同的数字

I want to create multi-index where first index is by Geography and second is by age group. 我想创建一个多索引,其中第一个索引是按地理位置划分的,第二个索引是按年龄组划分的。

Also is it possible to groupby w/o performing any functions at the end? 还有可能不进行任何功能的分组方式吗?

Output should be: 输出应为:

   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
.
.

In order to create a MultiIndex as specified, you can simply use DataFrame.set_index() : 为了创建指定的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

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

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