2016-05-07 148 views
0

在蟒的條件求和我具有類似於下面的一個大熊貓數據幀:的Python /大熊貓:列

  | AUG12    | UNDERLYING | VOL | 
      |---------------------|   |  | 
      | 45 | 49 | 50 | 55 |   |  | 
====================================================| 
2012-11-14 | 1 | 1 | 2 | 3 | 49   | ? | 
...   ... ... ... ... 

的任務是:對於每一行,找到其比UNDERLYING更大的列名(49 ),將值(2 + 3)相加並將結果放入VOL(5)。我怎樣才能在python中完成這項工作?提前謝謝了!

回答

1

你可以使用DataFrame.apply功能

def conditional_sum(row): 
    underlying = row['UNDERLYING'][0] # extra '[0]' is required due to multi leve index in column names 
    return row.loc['AUG12'].apply(lambda x: 0 if x < underlying else x).sum() 

df.apply(conditional_sum, axis=1) 
+0

這正是我一直在尋找。我必須用我的列的範圍來替換'AUG12'。但你的片段做到了! – sascha