2016-12-16 53 views
2

我有一個熊貓數據框,看起來像這樣:使用MultiIndex在數據框中插入新的列值?

  rank  num  rank num 
      2015  2015  2014 2014 
France 8  1200  9  1216 
Italy  11  789  10  788  

我想補充的多指標新列,被稱爲corrected_num,我希望此列的值是num的價值相應的行,從另一個字典得到一個數字,它看起來像這樣劃分:

b = {2015: 10, 2014: 12} 

換句話說,我想有這樣的事情結束了:

  rank  num  num_corrected rank num num_corrected 
      2015  2015  2015    2014 2014 2014 
France 8  1200  120    9  1216 101.3 
Italy  11  789  78.9    10  788 65.6 

到目前爲止,我的做法是遍歷每一行數據幀,然後在該行中的每一列,這樣的事情:

for i, row in df.iterrows(): 
    for year in df.num.columns: 
     df.set_value(i, 'num_corrected, ' + year, row.frequency[year]/b[year]) 

但當我嘗試這個我Jupyter筆記本死機,所以我希望有更好的辦法!

+0

這是很難說,如果你的年是柱狀多指標與否的第二級。你可以包含代碼來生成你的數據框嗎? – Alex

回答

1

設置

df = pd.DataFrame(
    [ 
     [8, 1200, 9, 1216], 
     [11, 789, 10, 788] 
    ], 
    ['France', 'Italy'], 
    pd.MultiIndex.from_product([['rank', 'num'], [2015, 2014]]) 
).sort_index(axis=1, level=1) 

b製作一系列

b = pd.Series({2015: 10, 2014: 12}) 

方法1

num_c = df.num/b 

cols = num_c.columns 
num_c.columns = [['num_corrected'] * len(cols), cols] 

pd.concat([df, num_c], axis=1) 

enter image description here

方法2

d1 = df.stack() 
d1['num_corrected'] = d1.num/d1.index.get_level_values(1).to_series().map(b).values 
d1.unstack().sort_index(axis=1, level=1) 

enter image description here

相關問題