Calculate difference between first non-zero value and last non-zero value through multiple instances in Pandas Series?

Viewed 920

I have a DataFrame with column col_c values of 0, positive integers, 0, negative integers, 0. I want to return a new column (col_d as shown below) with values calculating the difference between the first non-zero value and last non-zero value. The original DataFrame demonstrates col_c values:

   col_a col_b col_c
 1  AB    0     0     
 2  AB    0     0     
 3  AB    1     1     
 4  AB    1     2     
 5  AB    1     5     
 6  AB    1     3     
 7  AB    0     0     
 8  AB    0     0     
 9  AB   -1    -1     
10  AB   -1    -2     
11  AB   -1    -5     
12  AB   -1    -3     
13  AB    0     0
14  AB    0     0

I want to return a DataFrame as follows, where the values 2 in rows 6 and 12 are calculated from col_c as (3-1) = 2 and (-3 - -1) = -2:

   col_a col_b col_c col_d
 1  AB    0     0      0
 2  AB    0     0      0
 3  AB    1     1      0
 4  AB    1     2      0
 5  AB    1     5      0
 6  AB    1     3      2
 7  AB    0     0      0
 8  AB    0     0      0
 9  AB   -1    -1      0
10  AB   -1    -2      0
11  AB   -1    -5      0
12  AB   -1    -3      2
13  AB    0     0      0
14  AB    0     0      0
3 Answers
Related