【问题标题】:merge multiindex dataframe with unequal length合并长度不等的多索引数据帧
【发布时间】:2017-03-18 20:08:20
【问题描述】:

这是我的两个数据框

index = pd.MultiIndex.from_product([['a','b'],[1,2]],names=['one','two'])
df = pd.DataFrame({'col':[10,20,30,40]}, index = index)
df
          col
 one two     
 a   1     10
     2     20
 b   1     30
     2     40

index_1 = pd.MultiIndex.from_product([['a','b'],[1.,2],['abc','mno','xyz']], names = ['one','two','three'])
temp =  pd.DataFrame({'col1':[1,2,3,4,5,6,7,8,9,10,11,12]}, index = index_1)
temp
                col1
 one two three      
  a   1.0 abc       1
          mno       2
          xyz       3
      2.0 abc       4
          mno       5
          xyz       6
  b   1.0 abc       7
          mno       8
          xyz       9
      2.0 abc      10
          mno      11
          xyz      12

如何合并它们? 我试过了,这个

pd.merge(left = temp, right = df, left_on = temp.index.levels[0], right_on = df.index.levels[0])

但这不起作用

KeyError: "Index([u'a', u'b'], dtype='object', name=u'one') not in index"

如果我通过 reset_index() 将索引转换为列,则合并有效。但是,我希望在保留索引结构的同时实现这一点。

我想要的输出是:

【问题讨论】:

    标签: python pandas merge multi-index


    【解决方案1】:

    方法 1
    reset_index + merge

    df.reset_index().merge(temp.reset_index()).set_index(index_1.names)
    

    方法 2
    joinreset_index 部分

    df.join(temp.reset_index('three')).set_index('three', append=True)
    

    【讨论】:

    • 非常感谢,这行得通。我很长一段时间都在摆弄 pd.merge 和 pd.reset_index ,但并没有让我觉得我可以这样使用它们。你能建议我如何提高我在 Pandas 中处理时间序列数据的技能吗?
    • @SirajS。最好的方法是尝试在 stackoverflow 上回答这些问题……不开玩笑!
    猜你喜欢
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2020-04-10
    • 2019-02-27
    • 2015-01-02
    • 2021-01-10
    相关资源
    最近更新 更多