4

If I have a dataframe with n rows, is there a way to set the ith row to be sum of row[i] and row[i-1] and do this so that the assignment to earlier rows is reflected in the latter rows? I would really like to avoid loops if possible.

Example DF:

             SPY   AAPL   GOOG
2011-01-10  0.44  -0.81   1.80
2011-01-11  0.00   0.00   0.00
2011-01-12 -1.11  -2.77  -0.86
2011-01-13 -0.91  -4.02  -0.68

Sample pseudo code of summing two rows:

DF[2011-01-11] = DF[2011-01-10] + DF[2011-01-11]
DF[2011-01-12] = DF[2011-01-11] + DF[2011-01-12]

and so on.

1
  • I think you mean to sum along columns. I suggest you change that (in the title if possible) to make this easier to find for over users Commented Oct 16, 2016 at 16:00

2 Answers 2

1

based on your question, you are looking for a cumulative sum of each columns. you could use the cumsum() method

DF.cumsum()

               SPY    AAPL   GOOG
2011-01-10  0.4400 -0.8100 1.8000
2011-01-11  0.4400 -0.8100 1.8000
2011-01-12 -0.6700 -3.5800 0.9400
2011-01-13 -1.5800 -7.6000 0.2600
Sign up to request clarification or add additional context in comments.

2 Comments

No I did actually mean to say that.
i. e. row[i]=row[i-1]+row[i] but row[i-1] is not the original row but rather the sum of row[i-1] and row[i-2]
0

Use DF.shift()

DF + DF.shift()

Comments

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.