0

In python I have a pandas data frame similar to the one below:

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

The task is: For each row, find column names which are greater than UNDERLYING (49), sum the values (2+3) and put the result in to VOL (5). How can I accomplish this in python? Many thanks in advance!

1 Answer 1

1

You could use DataFrame.apply function

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)
Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly what I was looking for. I had to replace AUG12 with the range of my columns. But your snippet did the trick!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.