Merge two MultiIndex levels into one in Pandas

荒凉一梦 提交于 2019-12-04 02:26:09

Consider the pd.MultiIndex and pd.DataFrame, mux and df

mux = pd.MultiIndex.from_product([list('ab'), [2014, 2015], range(1, 3)])

df = pd.DataFrame(dict(A=1), mux)

print(df)

          A
a 2014 1  1
       2  1
  2015 1  1
       2  1
b 2014 1  1
       2  1
  2015 1  1
       2  1

We want to reassign to the index a list if lists that represent the index we want.

  • I want the 1st level the same

    df.index.get_level_values(0)
    
  • I want the new 2nd level to be a string concatenation of the current 2nd and 3rd levels but reverse the order

    df.index.map('{0[2]}/{0[1]}'.format)
    

df.index = [df.index.get_level_values(0), df.index.map('{0[2]}/{0[1]}'.format)]

print(df)

          A
a 1/2014  1
  2/2014  1
  1/2015  1
  2/2015  1
b 1/2014  1
  2/2014  1
  1/2015  1
  2/2015  1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!