haneulkim
haneulkim

Reputation: 4928

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

Upvotes: 0

Views: 42

Answers (1)

yatu
yatu

Reputation: 88236

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

Upvotes: 4

Related Questions