2017-08-17 55 views
1

我想添加哪些格式相同的數據幀的值。 爲〔實施例(Python2)結合多層列的熊貓數據框

>>> my_dataframe1 

     class1 score 
subject 1 2 3 
student 
0  1 2 5 
1  2 3 9 
2  8 7 2 
3  3 4 7 
4  6 7 7 

>>> my_dataframe2 

     class2 score 
subject 1 2 3 
student 
0  4 2 2 
1  4 4 14 
2  8 7 7 
3  1 2 NaN 
4  NaN 2 3 

,你可以看到,這兩個dataframes具有多層列主欄是「類分數」和子欄目是「主題」。 我想要做的是,讓總結數據框可以顯示這樣

  score 
subject 1 2 3 
student 
0  5 4 7 
1  2 1 5 
2  16 14 9 
3  4 6 7 
4  6 9 10 

其實,我可以通過

for i in my_dataframe1['class1 score'].index: 
    my_dataframe1['class1 score'].loc[i,:] = my_dataframe1['class1 score'].loc[i,:].add(my_dataframe2['class2 score'].loc[i,:], fill_value = 0) 

得到這個數據幀,但尺寸增大時,需要花費大量的時間來得到結果數據框,我認爲這不是解決問題的好方法。

回答

0

如果從第二個數據幀添加values,它會忽略索引

# you don't need `astype(int)`. 
my_dataframe1.add(my_dataframe2.values, fill_value=0).astype(int) 

     class1 score   
subject   1 2 3 
student      
0     5 4 7 
1     6 7 23 
2     16 14 9 
3     4 6 7 
4     6 9 10 

設置

my_dataframe1 = pd.DataFrame([ 
    [1, 2, 5], 
    [2, 3, 9], 
    [8, 7, 2], 
    [3, 4, 7], 
    [6, 7, 7] 
], pd.RangeIndex(5, name='student'), pd.MultiIndex.from_product([['class1 score'], [1, 2, 3]], names=[None, 'subject'])) 

my_dataframe2 = pd.DataFrame([ 
    [4, 2, 2], 
    [4, 4, 14], 
    [8, 7, 7], 
    [1, 2, np.nan], 
    [np.nan, 2, 3] 
], pd.RangeIndex(5, name='student'), pd.MultiIndex.from_product([['class2 score'], [1, 2, 3]], names=[None, 'subject'])) 
0

IIUC:

df_out = df['class1 score'].add(df2['class2 score'],fill_value=0).add_prefix('scores_') 

df_out.columns = df_out.columns.str.split('_',expand=True) 

df_out 

輸出:

 scores   
      1 2  3 
student     
0   5.0 4 7.0 
1   6.0 7 23.0 
2   16.0 14 9.0 
3   4.0 6 7.0 
4   6.0 9 10.0 
0

我會這樣做的方式是保持數據在同一個數據框中。你可以將兩者連接起來,你已經:

big_df = pd.concat([my_dataframe1, my_dataframe2], axis=1) 

然後在更大的數據幀綜上所述,指定level

big_df.sum(axis=1, level='subject')