Cumulative sum of data in new python column

Asked

Viewed 77 times

1

Hello personal I have a dataframe with input and output data per day my need and add to that dataframe a cumulative column are daily entries and exits so in excel I would have the following code

column A: input and output data column B = data from today’s column A + data from yesterday’s column B

having the following exit

# To B(formula) B(exit)
1 10 =A1+B0 10
2 20 =A2+B1 30
3 -5 =A3+B2 25
4 -10 =A4+B3 15
5 20 =A5+B4 35

for this from the header of my data frame I created a dictionary with indices starting at 1

dict={1:produto1, 2:produto2, 3:produto3}

and then a repeat structure that would create a new column for each iten of my dictionary concatenated with 'acc'

tcolunas = DataFrame.columns()
tcolunas = DataFrame.tolist()

conts = 1
for n in t colunas:
      x = str(tcolunas[conts-1]) + ' acc'
      DataFrame[x] = (DataFrame[dict[conts]] + DataFrame[x].shif(1))
      conts = conts + 1

The output gives me the sum by a line but then zeroing in, like this:

entrances/exits acc
0 0
99 99
30 129
0 30
0 0

I believe the program cannot iterate within the same column about itself would have some solution for this ?

  • correcting 
tcolunas = DataFrame.columns()
tcolunas = tcolunas.tolist()


1 answer

1

I believe what you need is the method cumsum()

Take the example:

Creating Dataframe

>>> import pandas as pd

>>> df = pd.DataFrame({"A": [10, 20, -5, -10, 20]})

>>> df
    A
0  10
1  20
2  -5
3 -10
4  20

Creating column with accumulated sum

>>> df["B"] = df["A"].cumsum()

>>> df
    A   B
0  10  10
1  20  30
2  -5  25
3 -10  15
4  20  35
>>>

I hope it helps

Browser other questions tagged

You are not signed in. Login or sign up in order to post.