Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values from previous row/value python

is it possible to add values from each row with value from previously define number in Python just like this:

base_value = 10

a b c
2 3 (expected. 2+3+base_value=10)
4 3 (expected. 4+3+15=22)
1 9 (expected. 1+9+22=32)
5 7 (expected. 5+7+32=44)
1 1 (expected. 1+1+44=46)
... 

Thank you in advance

like image 709
ShortHair Avatar asked Jun 07 '26 17:06

ShortHair


2 Answers

Use Series.add with Series.cumsum:

base_value = 10
df['c'] = df['a'].add(df['b']).cumsum().add(base_value)

print (df)
   a  b   c
0  2  3  15
1  4  3  22
2  1  9  32
3  5  7  44
4  1  1  46
like image 156
jezrael Avatar answered Jun 10 '26 08:06

jezrael


This is not the most efficient way but you can use this:

import pandas as pd

base_value = 10
c = []
df = pd.read_csv('a.csv')
for i in range(len(df['a'])):
    base_value = df['a'][i]  + df['b'][i] + base_value
    c.append(base_value)
df['c'] = c
like image 40
Divyessh Avatar answered Jun 10 '26 07:06

Divyessh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!