Binary operation broadcasting across multiindex

pandas

Solution

As discussed by me and @jreback in the issue opened to deal with this, a nice workaround to the problem involves doing the following:

- Move the non-matching index level(s) to columns using `unstack`

- Perform the multiplication/division

- Put the non-matching index level(s) back using `stack`

- Make sure the index levels are in the same order as they were before.

Here's how it works:

In [112]: x.unstack('country').mul(y, axis=0).stack('country').reorder_levels(x.index.names)
Out[112]: 
year  country  prod
1     A        1       100.0
      B        1       150.0
      A        2         2.0
      B        2         2.5
2     A        1       400.0
      B        1       500.0
      A        2         6.0
      B        2         7.0
dtype: float64

I think that's rather good, and should be pretty efficient.

Problem

can anyone explain why broadcasting across a multiindexed series doesn't work? Might it be a bug in pandas (0.12.0)? ``` x = pd.DataFrame({'year':[1,1,1,1,2,2,2,2], 'country':['A','A','B','B','A','A','B','B'], 'prod':[1,2,1,2,1,2,1,2], 'val':[10,20,15,25,20,30,25,35]}) x = x.set_index(['year','country','prod']).squeeze() y = pd.DataFrame({'year':[1,1,2,2],'prod':[1,2,1,2], 'mul':[10,0.1,20,0.2]}) y = y.set_index(['year','prod']).squeeze() ``` From the description of matching/broadcasting behavior from the pandas docs I would expect to be able to multiply `x` and `y` and have the values of `y` broadcast across each `country`, giving: ``` >>> x.mul(y, level=['year','prod']) year country prod 1 A 1 100.0 2 2.0 B 1 150.0 2 2.5 2 A 1 400.0 2 6.0 B 1 500.0 2 7.0 ``` But instead, I get: ``` Exception: Join on level between two MultiIndex objects is ambiguous ``` (Note that this is a variation on the theme of this question.)

Original source