pandas 多索引按行重新索引 [英] pandas multiindex reindex by rows

查看:33
本文介绍了 pandas 多索引按行重新索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这很简单,但我没有找到解决方案.我有一个这样的数据框

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')

我尝试使用年"获得 0 级的多索引,月"获得 1 级的多重索引.销售"将保留为列.

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

例如像这样:

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

推荐答案

可以传一个列表

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

这篇关于 pandas 多索引按行重新索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆