简体   繁体   中英

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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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