0

I have a data frame like this,

Date        Open    High to Low   X
27-Feb-15   A           P         x1
26-Feb-15   B           Q         x2
25-Feb-15   C           R         x3
24-Feb-15   D           S         x4

i need to calculate X column values like follows,

x1 = (P+Q)/B
x2 = (Q+R)/C
   '
   '

is there any way to do this not using for loops using pandas?

1 Answer 1

2

Use Rolling.sum with division by Series.div:

print (df)
        Date  Open  High to Low   X
0  27-Feb-15    10            1  x1
1  26-Feb-15    20            2  x2
2  25-Feb-15    50            3  x3
3  24-Feb-15   100            4  x4

df['X'] = df['High to Low'].rolling(2).sum().div(df['Open'])
print (df)
        Date  Open  High to Low     X
0  27-Feb-15    10            1   NaN
1  26-Feb-15    20            2  0.15
2  25-Feb-15    50            3  0.10
3  24-Feb-15   100            4  0.07

If necessary shift data add Series.shift:

df['X'] = df['High to Low'].rolling(2).sum().div(df['Open']).shift(-1)
print (df)
        Date  Open  High to Low     X
0  27-Feb-15    10            1  0.15
1  26-Feb-15    20            2  0.10
2  25-Feb-15    50            3  0.07
3  24-Feb-15   100            4   NaN
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much jezrael ,this is exactly i wanted.
@sanuja - Thanks, glad to help. Don't forget to accept the answer, if it suits you! :)

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.