Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply two Series with MultiIndex in pandas

Tags:

python

pandas

I am trying to multiply two Series, both 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 reindex the 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 method to perform this operation in just 1 step.

like image 595
Andrea Zonca Avatar asked Nov 03 '22 19:11

Andrea Zonca


1 Answers

Try this. reset_index removes the last level, so they are the same when you multiply

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

Since you want the original index (and the shape 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
like image 79
Jeff Avatar answered Nov 08 '22 05:11

Jeff