João Machado
João Machado

Reputation: 325

Is there a way to use previous row value in pandas' apply function when previous value is iteratively summed ?or an efficient way?

I have a dataframe with some columns and I would like to apply the following transformation in an efficient manner.

Given the Dataframe below:

   C    D
 ===========
  Nan  10
  0  22 
  2  280
  4  250
  6  270

It should be transformed in such a way I can get the following output:

   C    D
 ===========
  Nan  10
  0  22 
  2  280
  6  252
  12 276 

Note that:

C[i] = C[i] + C[i - 1] + ... + C[0]

and

D[i] = D[i] + C[i - 1]

NaN values should be filtered.

Thx!

Upvotes: 2

Views: 294

Answers (2)

AdrianoHRL
AdrianoHRL

Reputation: 26

df['C'] = df['C'].cumsum()
df['D'] = df['D'].add(df['C'].shift(1).fillna(0))

Output:

      C      D
0   NaN      10.0
1   0.0      22.0
2   2.0     280.0
3   6.0     252.0
4   12.0    276.0

Upvotes: 1

harpan
harpan

Reputation: 8631

IIUC, you need:

df['C'] = df['C'].add(df['C'].shift(1).fillna(0))
df['D'] = df['D'].add(df['C'].shift(1).fillna(0))

Output:

       C       D
0   NaN      10.0
1   0.0      22.0
2   2.0     280.0
3   6.0     252.0
4   10.0    276.0

Upvotes: 1

Related Questions