2013-10-22 69 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