Reputation: 109
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
Upvotes: 3
Views: 1562
Reputation: 863521
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
Upvotes: 3
Reputation: 17911
You can use:
df['c'] = df['a'] + df['b'] # add both columns
df.iat[0, 'c'] += 10 # add 10 to the first cell
df['c'] = df['c'].cumsum() # cumulative sum
Output:
a b c
0 2 3 15
1 4 3 22
2 1 9 32
3 5 7 44
4 1 1 46
Upvotes: 1
Reputation: 1413
you can do:
df=pd.DataFrame({'a':[2,4,1,5,1],'b':[3,3,9,7,1]})
base=10
df['c']=base+(df['a']+df['b']).cumsum()
df
Out[32]:
a b c
0 2 3 15
1 4 3 22
2 1 9 32
3 5 7 44
4 1 1 46
Upvotes: 1
Reputation: 2721
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
Upvotes: 1