在 pandas 中将两个MultiIndex级别合并为一个级别 [英] Merge two MultiIndex levels into one in Pandas

查看:189
本文介绍了在 pandas 中将两个MultiIndex级别合并为一个级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MultiIndexed的Pandas数据框.第二级包含年份([2014,2015]),第三级包含月份号([1、2,..,12]).我想将这两个合并成一个单一的级别,例如-[1/2014,2/2014 ...,6/2015].怎么办呢?

I have a Pandas data frame which is MultiIndexed. The second level contains a year ([2014,2015]) and the third contains the month number ([1, 2, .., 12]). I would like to merge these two into a single level like - [1/2014, 2/2014 ..., 6/2015]. How could this be done?

我是熊猫的新手.搜索了很多,但找不到任何类似的问题/解决方案.

I'm new to Pandas. Searched a lot but could not find any similar question/solution.

我找到了一种避免完全与

I found a way to avoid having to do this altogether with the answer to this question. I should have been creating my data frame that way. This seems to be the way to go for indexing by DateTime.

推荐答案

考虑pd.MultiIndexpd.DataFramemuxdf

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)

  • 我希望新的2级是当前2级和3级的字符串连接,但顺序相反

  • 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
    

    这篇关于在 pandas 中将两个MultiIndex级别合并为一个级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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