我试图将两个Series
乘以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
问题是我无法重新索引Series
从 2 到 3 的级别:
data_2levels.reindex(data_3levels.index, level=["l1","l2"])
Exception: Join on level between two MultiIndex objects is ambiguous
我找到了这个解决方法:
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
但我认为应该有一种方法可以在一个步骤中执行此操作。