简体   繁体   中英

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

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

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