2016-12-05 21 views
0

鑑於DF 'AB':如何在多級數據框上正確使用.loc?

A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]], 
     columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5]) 
B = pd.DataFrame([[3, 3, 3], [2, 2, 2], [4, 4, 4], [5, 5, 5], [6, 6, 6]], 
     columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5]) 

A.columns = pd.MultiIndex.from_product([['A'], A.columns]) 
B.columns = pd.MultiIndex.from_product([['B'], B.columns]) 
AB = pd.concat([A, B], axis = 1) 

我想增加一列 '新的' 到電平 'B',基於列的[ 'B', 'C']的條件。我期待專門使用df.loc,像這樣:

AB['B', 'new'] = 0 
AB.loc[AB['B', 'C'] >= 3, 'new'] = 1 

的問題是,此過程創建一個「新」的DF代替填充柱[「B」,「新」]。

所需的輸出是:

A   B 
    A B C A B C new 
1 1 5 2 3 3 3 1 
2 2 4 4 2 2 2 0 
3 3 3 1 4 4 4 1 
4 4 2 2 5 5 5 1 
5 5 1 4 6 6 6 1 

回答

1

使用元組,以引用的多級索引/列:

AB[('B', 'new')] = 0 
AB.loc[AB[('B', 'C')] >= 3, ('B', 'new')] = 1 

可替換地,在一個單一的線路:

AB[('B', 'new')] = AB[('B', 'C')].ge(3).astype(int) 

所產生的輸出:

A  B   
    A B C A B C new 
1 1 5 2 3 3 3 1 
2 2 4 4 2 2 2 0 
3 3 3 1 4 4 4 1 
4 4 2 2 5 5 5 1 
5 5 1 4 6 6 6 1 
+0

很酷,我嘗試過元組之前,出於某種原因,我認爲它沒有工作。你的答案獎金是學習df.ge()。謝謝 – hernanavella

相關問題