【问题标题】:Concatenating Index to MultiIndex in Pandas在 Pandas 中将索引连接到 MultiIndex
【发布时间】:2019-02-15 09:07:41
【问题描述】:

我有 pandas MultiIndex 这样的对象:

>>> import pandas as pd
>>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
>>> multi = pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))
>>> print(multi)

MultiIndex(levels=[[1, 2], ['blue', 'red']],
           labels=[[0, 0, 1, 1], [1, 0, 1, 0]],
           names=['number', 'color'])

我想从另一个来源追加第三个索引列。

>>> idx = pd.Index(['a', 'a', 'a', 'b'], name='letter')

最终结果应该是包含所有三列的MultiIndex

>>> pd.MagicFunctionICanNotFind(multi, idx)

MultiIndex(levels=[[1, 2], ['blue', 'red'], ['a', 'b']],
           labels=[[0, 0, 1, 1], [1, 0, 1, 0], [0, 0, 0, 1]],
           names=['number', 'color', 'letter'])

当我尝试使用MultiIndex.append() 函数时,它将我的新索引值连接到我的索引对象的底部,而不是作为一个新级别。我还查看了想要做类似事情的this question,但是它正在使用数据框,并且由于超出此问题范围的长期复杂原因,我正在使用索引对象。我一直在尝试使用两个索引对象的底层values 的一切都变得相当复杂,以至于它似乎不是最好的前进道路。这一定是 pandas 代码库中比较频繁发生的事情,有没有优雅的解决方案?

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    创建一个模拟 DataFrame 并使用 set_index:

    pd.DataFrame(index=multi).set_index(idx, append=True).index
    

    MultiIndex(levels=[[1, 2], ['blue', 'red'], ['a', 'b']],
               labels=[[0, 0, 1, 1], [1, 0, 1, 0], [0, 0, 0, 1]],
               names=['number', 'color', 'letter'])
    

    【讨论】:

      猜你喜欢
      • 2020-08-01
      • 2018-12-20
      • 2018-12-29
      • 2018-12-21
      • 1970-01-01
      • 2021-03-27
      • 2020-04-12
      • 2018-06-07
      • 2013-02-04
      相关资源
      最近更新 更多