Product between MultiIndex and a list

78 Views Asked by At

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 ?

3

There are 3 best solutions below

0
mozway On BEST ANSWER

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])
1
Yogesh On

You can try the below:

import pandas as pd

mux = pd.MultiIndex.from_tuples([(1, 1), (2, 3)])
l = [4, 5]

# Create the MultiIndex by broadcasting the lists
result = pd.MultiIndex.from_arrays([mux.get_level_values(0), mux.get_level_values(1), l * len(mux)])

print(result)
`
0
sammywemmy On

A possibly more efficient way is to do the combination at an array level, using np.repeat and np.tile, before building a new MultiIndex. This way, you are dealing with the arrays, instead of building a DataFrame only to return to an Index. As always, test with your actual data:

len_mux = len(mux)
len_l = len(l)
mux = mux.repeat(len_l)
mux = [mux.get_level_values(n) for n in range(mux.nlevels)]
l = np.tile(l, len_mux)
mux.append(l)
pd.MultiIndex.from_arrays(mux)
MultiIndex([(1, 1, 4),
            (1, 1, 5),
            (2, 3, 4),
            (2, 3, 5)],
           )