简体   繁体   中英

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!

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM