How to create a new column takes the value from the sum of another column each row?

54 views Asked by At

Like taking the value from the first row 60, then add it to the new value from the next row and so on, like the example of the below table.

     field       A                             B
0      u       60.0                           60.0
1      v       78.0   >>     60.0  + 78.0  =  138.0
2      w       42.0   >>     138.0 + 42.0  =  180.0
3      x       61.0   >>     180.0 + 61.0  =  241.0
4      y       36.0   >>     241.0 + 36.0  =  277.0
2

There are 2 answers

0
Nathan On BEST ANSWER

Pandas has a built-in "cumulative sum"

import pandas as pd

df = pd.DataFrame(
    {
        "field": ["u", "v", "w", "x", "y"],
        "A": [60, 78, 42, 61, 36],
    }
)

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

print(df)

Output:

  field   A    B
0     u  60   60
1     v  78  138
2     w  42  180
3     x  61  241
4     y  36  277
0
Rankstrait On

assuming that you are using a Pandas dataframe and it is named df you can do that operation in this way (without using builtin pandas .cumsum package):

columns_A = df["A"] #obtain the element of the columns A as a series
new_col= []
for i in range(len(columns_A)):
    if i <=0: # the first element tha can't be sum up
        new_col.append(a[i])
    else: # after the first element we start with cumulative sum
        new_col.append(new_col[i-1]+a[i]) #here with new_row[i-1] we obtain the previous element respect the 
        #the current one and thanks to that we can obtain the cumulative sum
df["B"] = new_col #here we assign the name of the column and add the values to the dataframe