Search code examples
pythonpandasmulti-indexcartesian-product

Product between MultiIndex and a list


I have a MultiIndex object with 2 levels:

import pandas as pd
mux = pd.MultiIndex.from_tuples([(1,1), (2,3)])
>>>
MultiIndex([(1, 1),
            (2, 3)],
           )

I want to multiply it by a list l=[4,5], I tried

pd.MultiIndex.from_product([mux.values, [4,5]])
>>>
MultiIndex([((1, 1), 4),
            ((1, 1), 5),
            ((2, 3), 4),
            ((2, 3), 5)],
           )

I managed to get my expected result with

from itertools import product
pd.MultiIndex.from_tuples([(*a, b) for a, b in product(mux, [4,5])])
>>>
MultiIndex([(1, 1, 4),
            (1, 1, 5),
            (2, 3, 4),
            (2, 3, 5)],
           )

Is there a better way to do this operation ?


Solution

  • I think your approach is quite reasonable.

    Another option using a cross-merge with an intermediate DataFrame format:

    pd.MultiIndex.from_frame(mux.to_frame().merge(pd.Series([4, 5], name=2), how='cross'))
    

    Output:

    MultiIndex([(1, 1, 4),
                (1, 1, 5),
                (2, 3, 4),
                (2, 3, 5)],
               names=[0, 1, 2])