Search code examples
pythonpandasdataframemulti-index

Multiply lower level columns with list for each row in pandas


I am new to pandas and have a multiIndex dataframe df with two level columns like this

        one                zero
          y         x         y         x
0  0.625695  2.149377  0.006123  0.854284
1 -1.392909  0.849853  0.005477  1.743587

Now I want to multiply each row of each level=1 with a list of the same length.

So far I only managed to achieve this with something like df.stack(level=0).mul([1.5,2.5]).unstack(level=0).swaplevel(0,1,axis=1).T.sort_index().T

The output should look like this

         one                    zero
           x           y           x           y
0   3.224066    1.564237    1.281426    0.015307
1   1.274779   -3.482272    2.615381    0.013692

I am sure there must be an easier/more elegant way to achieve this. Can someone point me in the right direction?


Solution

  • Do you mean:

    df.mul(pd.Series({'x':1.5, 'y':2.5}), level=1)
    

    Output:

            one                zero          
              y         x         y         x
    0  1.564237  3.224066  0.015307  1.281426
    1 -3.482272  1.274780  0.013692  2.615381