Search code examples
pythonpandasmulti-index

pandas multiindex reindex by rows


I thought it is simple, but I didn't find the solution. I have a data frame like this

df = pd.DataFrame({'month': [1, 4, 7, 10],
                'year': [2012, 2012, 2013, 2013],
                'sale': [55, 40, 84, 31]})
df.set_index('month')

I try to get a Multiindex with level 0 with 'year', and level 1 with 'month'. 'sale' will stay as column.

for example like this:

year  month sale 
2012  1     55
      4     40 
2013  7     84
      10    31

Solution

  • You can pass a list

    df=df.set_index(['year','month'])
    df
                sale
    year month      
    2012 1        55
         4        40
    2013 7        84
         10       31