2013-10-22 68 views
3

我有类似这样大熊猫师(.div)与多指标

df = pd.DataFrame(np.random.randint(2, 10, size = (5, 2))) 
df.index = pd.MultiIndex.from_tuples([(1, 'A'), (2, 'A'), (4, 'B'), 
      (5, 'B'), (8, 'B')]) 
df.index.names = ['foo', 'bar'] 
df.columns = ['count1', 'count2'] 
df 

一些东西,得到:

 count1 count2 
foo bar  
1 A 6  7 
2 A 2  9 
4 B 6  7 
5 B 4  6 
8 B 5  6 

我也有通过同样从某处else- -obtained总数的列表'富' 指数:

totals = pd.DataFrame([2., 1., 1., 1., 10.]) 
totals.index = [1, 2, 4, 5, 8] 
totals.index.names = ['foo'] 
totals 

其给出:

 0 
foo 
1 2 
2 1 
4 1 
5 1 
8 10 

我怎么能由是在总计 foo的数字除以DFCOUNT1COUNT2)的所有列? (因此,我需要通过'富'数字匹配)

我检查了this question,看起来它应该做的伎俩,但我无法弄清楚。

我试图

df.div(totals, axis = 0) 

和改变DIV水平选项,但没有成功。

与往常一样,非常感谢您的时间

+0

不幸的是,我没有时间去成为一个更详细的解答。以下链接是否可以帮助你? http://stackoverflow.com/questions/13940753/aligning-dataframes-with-same-columns-different-index-levels –

+0

这是一个重复的:http://stackoverflow.com/questions/19501510/divide-entire- pandas-multiindex-dataframe-by-dataframe-variable – Jeff

+0

嗨,我检查了这些答案并尝试使用选项level = 0或level ='foo',但它不起作用。 Roman Pekar的回答如下,但我不明白为什么。 – cd98

回答

2

totals[0]作品使用values列表:

df.div(totals[0].values, axis=0) 

但它没有考虑指数从totals考虑。不知道为什么,这并不工作:

df.div(totals[0], level=0, axis=0) 
+0

谢谢,这绝对有效!我想知道为什么其他选项不起作用,虽然 – cd98

+2

'totals [0]''拿出一个现有的水平,所以说''水平= 0''使它在特定的水平上广播;只使用“总计”的原因不起作用,因为它具有所有开始的级别。 – Jeff

1

尝试:

df.div(totals[0],axis='index',level='foo') 

     count1 count2 
foo bar     
1 A  1.0  4.5 
2 A  4.0  8.0 
4 B  5.0  9.0 
5 B  5.0  5.0 
8 B  0.9  0.5 

也:

totals = pd.DataFrame([2., 1., 1., 1., 10.]) 
totals.index = [[1, 2, 4, 5, 8],['A', 'A', 'B', 'A', 'B']] 
totals.index.names = ['foo','bar'] 
totals 
      0 
foo bar  
1 A  2.0 
2 A  1.0 
4 B  1.0 
5 A  1.0 
8 B 10.0 

df[['count1','count2']].div(totals[0],axis='index') 
     count1 count2 
foo bar     
1 A  1.0  4.5 
2 A  4.0  8.0 
4 B  5.0  9.0 
5 A  NaN  NaN 
    B  NaN  NaN 
8 B  0.9  0.5 
+0

多级指标分割。 – user8641707