Home > Net >  Python - Pandas DF Sumproduct in a loop
Python - Pandas DF Sumproduct in a loop

Time:09-08

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...

CodePudding user response:

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

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

CodePudding user response:

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

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