Lucas_A
Lucas_A

Reputation: 15

Iterating Rows and adding the value from the row above- Python

I have a column that acts as a ledger. The values in each row is either a receipt (positive) and an outbound (negative). I am looking to create an additional column that takes the value from the row above and adds/subracts the current value and gives a total enter image description here

Below is the code I have tried, but all it does is write the values into another column:

mylist, df["consumption"]= []," " 
for i in range(1, len(thc) + 1):
    j = df.columns.get_loc('Ledger')
    x = (df.iat[i - 1, j])
    mylist.append(x)
df["consumption"] = mylist

I would like the consumption column to look like: enter image description here

The intent is to use this df to create a forecast and a lined plot tracking consumption.

Thanks for the help

Upvotes: 0

Views: 46

Answers (2)

Vinay Khatri
Vinay Khatri

Reputation: 328

Let's take the above data as a 2d array where id represent index 0, transaction represents index 1, date represent index 2 and ledger represents index value 3.

so we will have an 2-d array structure like

[ [id1, transaction1, date1, ledger1 ], [id2, transaction2, date2,ledger2 ],.... ]

Now we want to add a new column consumption to each row which will be the sum of current legder and previous ledger and it will represent the 4th index value for each row.

account =  [    [ 0 , "Beg bal2019-2020 ",  " 2019-09-05" , 16875],
                [ 1 , "3072 ",  " 2019-09-05" , -50],
                [ 2 , "30874 ",  " 2019-09-05" , -50],
                [ 3 , "247499 ",  " 2019-09-05" , -50],
           ]

current = 0
for row in account:
    row.append(current + row[3])
    current =row[4]

for i in account:
    print(i)

Output

[0, 'Beg bal2019-2020 ', ' 2019-09-05', 16875, 16875]
[1, '3072 ', ' 2019-09-05', -50, 16825]
[2, '30874 ', ' 2019-09-05', -50, 16775]
[3, '247499 ', ' 2019-09-05', -50, 16725]

Upvotes: 0

deadshot
deadshot

Reputation: 9071

You can use df.cumsum()

df["consumption"] = df['Ledger'].cumsum()

Upvotes: 1

Related Questions