Skip to content
Advertisement

Python: concatenate pandas multiindex

I need to generate a pd.DataFrame with columns being composed by a list and a Multiindex object, and I need to do it before filling the final dataframe with data.

Say the columns are ['one', 'two'] and the multiindex obtained from from_product:

JavaScript

I would like to get a list of columns which looks like this:

JavaScript

One possible solution would be to use two different and separate Multiindex, one with a dummy column, both generate by from_product

JavaScript

How could I get to this?

JavaScript

I have tried several trivial solutions, but each gave me a different error or a wrong result

JavaScript
JavaScript
JavaScript

Thank you for your advices

Advertisement

Answer

If possible, the best is create MultiIndex in index by columns one, two and then MultiIndex in columns by pairs – so not mixed non multiindex with multindex values:

JavaScript

Use Index.append:

JavaScript

Or Index.union with sort=False:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement