Search code examples
pythonpandassubtraction

Cumulative subtraction with two columns in pandas


I have the table where I have 2 values for each day. I need to subtract the Val1 - Val2 row by row. E.g.:

          day   Val1    Val2
1    20230310    100     50
2    20230311    NaN     10
3    20230312    NaN      5
4    20230313    NaN     -3
5    20230314    NaN     40

How it should look like at the end:

          day   Val1    Val2
1    20230310    100     10
2    20230311     50     50
3    20230312     45      5
4    20230313     48     -3
5    20230314      8     40

Below is the same example but with the logic, not only the results:

          day   Val1        Val2
1    20230310    100         10
2    20230311    100-50=50   50
3    20230312    50-5=45      5
4    20230313    45-(-3)=48  -3
5    20230314    48-40=8     40

Solution

  • You can use:

    df['Val1'] = df['Val1'].fillna(-df['Val2']).cumsum()
    print(df)
    
    # Output
            day   Val1  Val2
    1  20230310  100.0    10
    2  20230311   50.0    50
    3  20230312   45.0     5
    4  20230313   48.0    -3
    5  20230314    8.0    40