Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas minus same row value with next row value

Time Agg Value Needed Value
10:55:00 178.0 322.0 322
11:00:00 354.0 (322-354)-32
11:05:00 354.0 (-32-354)-386
11:10:00 354.0 (-386-next Agg nu)

How can I calculate the needed value field,

for 1st row it takes the value field as it is,

for 2nd row it takes 2nd row needed value – 3rd row Agg value

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for 3rd row, 3rd row needed value -4th row agg

>Solution :

use cumsum to get cumulative sum of Agg, then subtract Value:

first_val = float(df['Value'].iloc[0])
df['Needed'] = first_val - df['Agg'].iloc[1:].cumsum()
df['Needed'] = df['Needed'].fillna(first_val)

Output:

        Time    Agg   Value        Needed Value  Needed
0  10:55:00   178.0  322.0                  322   322.0
1  11:00:00   354.0      -         (322-354)-32   -32.0
2  11:05:00   354.0      -        (-32-354)-386  -386.0
3  11:10:00   354.0      -   (-386-next Agg nu)  -740.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading