Multiindex from product giving nested tuples

Viewed 24

I need to create a dataframe with multiindices in one tuple, like so:

('2021C','Academic Info','Degree')

but I am only able to create a nested tuple, like this:

('2021C',('Academic Info','Degree'))

with pd.MultiIndex.from_product:

import pandas as pd

terms = ['2021C', '2022A', '2020C', '2021A', '2019A', '2019B', '2019C',
       '2020A', '2021B', '2020B']

tuples = [('Academic Info','Degree'),
('Academic Info','Major'),
('Demographic Info','Military'),
('Demographic Info','Army')
]

multiindex = pd.MultiIndex.from_product([terms, tuples],
                           names=['Term', 'Data Type'])

Output:

>>> multiindex

MultiIndex([('2021C',      ('Academic Info', 'Degree')),
            ('2021C',       ('Academic Info', 'Major')),
            ('2021C', ('Demographic Info', 'Military')),

This does not actually convert into the three multiindices I need for my dataframe.

This example has been abbreviated and the real life data contains many more columns than shown.

1 Answers

Flatten the tuples inside a comprehension then create a new multiindex

pd.MultiIndex.from_tuples((t, *v) for t in terms for v in tuples)

MultiIndex([('2021C',    'Academic Info',   'Degree'),
            ('2021C',    'Academic Info',    'Major'),
            ('2021C', 'Demographic Info', 'Military'),
            ('2021C', 'Demographic Info',     'Army'),
            ....
Related