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

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Thank you.
But is it possible to do that using groupby?
If what you want is to create a MultiIndex dataframe, this is the correct way. Groupbys are intended to apply some aggregation function over the groups

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.