TourEiffel
TourEiffel

Reputation: 4414

Python - Pandas DF Sumproduct in a loop

What would be the fastest way to do the sum product of the below DF

A B
2 6
5 5
7 5
8 2
6 11

I have a for loop :

for i in range(len(DF)) :
   Sumproduct = 0

What I aim to do in this for loop is for example if

i=1 then sumproduct = 2*6
i=2 then sumproduct = 2*6+5*5
i=3 then sumproduct = 2*6+5*5+7*5

Explanation in table :

A B SumProduct
2 6
5 5 2x6
7 5 2x6+5x5
8 2 2x6+5x5+7x5
6 11 2x6+5x5+7x5+8x2

ect...

Upvotes: 0

Views: 45

Answers (2)

rhug123
rhug123

Reputation: 8768

You could use prod() and cumsum() with shift()

df.prod(axis=1).cumsum().shift()

Upvotes: 3

Quang Hoang
Quang Hoang

Reputation: 150735

That'll be cumsum on the product of the two columns then shift down:

df['SumProduct'] = df['A'].mul(df['B']).cumsum().shift()

Upvotes: 1

Related Questions