Multiply two series with MultiIndex in pandas

I am trying to multiply two Series , as with MultiIndex :

 import pandas as pd tuples = [(0, 100, 1000),(0, 100, 1001),(0, 100, 1002), (1, 101, 1001)] index_3levels=pd.MultiIndex.from_tuples(tuples,names=["l1","l2","l3"]) tuples = [(0, 100), (1, 101)] index_2levels=pd.MultiIndex.from_tuples(tuples,names=["l1","l2"]) data_3levels = pd.Series(1, index=index_3levels) data_2levels = pd.Series([2,3], index=index_2levels) print data_3levels l1 l2 l3 0 100 1000 1 1001 1 1002 1 1 101 1001 1 dtype: int64 print data_2levels l1 l2 0 100 2 1 101 3 dtype: int64 

The problem is that I cannot override Series from 2 to 3 levels:

 data_2levels.reindex(data_3levels.index, level=["l1","l2"]) Exception: Join on level between two MultiIndex objects is ambiguous 

I found this workaround:

 for l1 in [0,1]: data_3levels[l1] *= data_2levels[l1].reindex(data_3levels[l1].index, level="l2") print data_3levels l1 l2 l3 0 100 1000 2 1001 2 1002 2 1 101 1001 3 dtype: int64 

But I think there should be a way to complete this operation in just 1 step.

+4
source share
2 answers

Try it. reset_index deletes the last level, so they are the same when multiplying

 In [25]: x = data_3levels.reset_index(level=2,drop=True)*data_2levels 

Since you want the original index (and the form hasn't changed), this works.

 In [26]: x.index=data_3levels.index In [27]: x Out[27]: l1 l2 l3 0 100 1000 2 1001 2 1002 2 1 101 1001 3 dtype: int64 
+1
source

There is a workaround until a β€œpleasant” solution arises through various extension requests.

You can simply:

  • unstack level of problem index (s)
  • do the multiplication
  • stack level of problematic indices back.

Like this:

 In [92]: data_3levels.unstack('l3').mul(data_2levels, axis=0).stack() Out[92]: l1 l2 l3 0 100 1000 2 1001 2 1002 2 1 101 1001 3 dtype: float64 
+1
source

Source: https://habr.com/ru/post/1489704/


All Articles