Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Subtract a column from another column if a condition is met, otherwise subtract from a different column?

I’m working with trading data and Pandas. Given a 4-column OHLC pandas DataFrame that is 100 rows in length, I’m trying to calculate if an "Upper Shadow" exists or not for an individual row and store the result in its own column. To calculate if an "Upper Shadow" exists all you have to do is take the high (H) value of the row and subtract the open (O) value if the close (C) value is less than the open value. Otherwise, you have to subtract the close value.

Right now I’m naively doing this in a for loop where I iterate over each row with an if statement.

for index, row in df.iterrows():
    if row["close"] >= row["open"]:
        df.at[index,"upper_shadow"]=float(row["high"]) - float(row["close"])
    else:
        df.at[index,"upper_shadow"]=float(row["high"]) - float(row["open"])

Is there a better way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use np.maximum to calculate the maximum of close and open in a vectorized way:

import numpy as np
df['upper_shadow'] = df['high'] - np.maximum(df['close'], df['open'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading