Barker
Barker

Reputation: 2094

Concatenating Index to MultiIndex in Pandas

I have pandas MultiIndex object like so:

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

I want to append a third index column from another source.

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

The final result should be a MultiIndex containing all three columns:

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

When I tried using the MultiIndex.append() function, it concatenated my new index values to the bottom of my index object instead of as a new level. I also looked at this question that wanted to do something similar, however that was working with a data frame, and here for long complicated reasons beyond the scope of this question, I am working with index objects. Everything I have been trying using the underlying values of the two index objects has been getting rather complicated to the point that it doesn't seem to be the best path forward. This has to be something that happens relatively frequently in the pandas codebase, is there an elegant solution?

Upvotes: 1

Views: 76

Answers (1)

user3483203
user3483203

Reputation: 51155

Create a mock DataFrame and use 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'])

Upvotes: 1

Related Questions