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

Iterating Pandas DF, Finding Sum After Loop

I’m trying to find the sum of the variable "candle" in the code below, but not sure how to write the code. I know someone is going to suggest using NumPy, but I don’t even know where to begin with that.

for index, row in df.iterrows():

    openPrice = row['open']
    closePrice = row['close']

    if closePrice - openPrice >= 0:
        candle = 0
    elif closePrice - openPrice <= 0:
        candle = 1  

I’m looping through a dataframe that contains stock prices (open and close). I want to find the difference between the two and find the sum of the times the output is =1. Let’s say the rows are: 1, 0, 0, 1. The sum should be 2.

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 :

Consider following dataframe:

   open  close
0    20     10
1    20     30
2    20     30
3    20      5

Then you can do:

df["col3"] = (df["close"] - df["open"] < 0).astype(int)
final_sum = df["col3"].sum()

print(df)
print(f"{final_sum=}")

This prints:

   open  close  col3
0    20     10     1
1    20     30     0
2    20     30     0
3    20      5     1

final_sum=2
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