2

I have a pandas dataframe with over 10k rows. I need to iterate through every row and do math based on the value of the previous row after it's updated. For loop is very slow.

Example DF:

a  b  c
1  2  3
2  3  4
3  4  5

for loop example:

for i in range(1,len(DF)):
  DF['b'] = DF['b'].[i-1]+DF['c']

I also tried

DF['b'] = DF['b'].shift(1)+DF['c']

but that won't use the updated value 'b'.

What is the best way to do such calculations?

ANSWERED: loc and iloc helps. The best way to do this is:

for i in range(1, len(DF)):
  DF.loc[i, 'b'] = DF.loc[i-1, 'b'] + DF.loc[i, 'c']
7
  • 2
    Are you sure you don't mean range(1,len(DF)):? Commented Jun 22, 2015 at 20:18
  • 2
    The particular math you wish to do is important. If it is simply addition, you could use cumsum. If it is more complicated, there may be no way to avoid looping over the rows. In that case, you may need Cython to boost performance. Commented Jun 22, 2015 at 20:23
  • 1
    @TigerhawkT3 UPDATED. I was translating an R script to Python. Commented Jun 22, 2015 at 20:24
  • 2
    It's impossible to say without seeing the actual math. Commented Jun 22, 2015 at 20:29
  • 1
    You need to be specific. Given your description the obvious question is why not call cumsum on both columns? A minimal working example would be helpful. The devil is in the details... Commented Jun 22, 2015 at 20:45

1 Answer 1

1

Use iloc

for i in range(1,len(DF)):
    DF.iloc[i]['b'] = DF.iloc[i-1]['b']+DF.iloc['i']['c']
Sign up to request clarification or add additional context in comments.

2 Comments

This helped a little, but yields the SettingWithCopyWarning. I changed it to DF.loc[i, 'b'] = DF.loc[i-1, 'b']+DF.loc['i', 'c'] and it's much faster.
Yes, you can also turn off the SettingWithCopyWarning using following command pa.options.mode.chained_assignment = None # default='warn'

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.