Sateesh
Sateesh

Reputation: 31

Subtracting rows from other rows in a dataframe

I want to subtract the row having some value with the row having other value.Suppose I have a data frame having 16 rows and two columns. I need difference of values column for first 8 and end 8 in flag column after and before 0's.


    flag    values
     0       456
     0       789
     8       56
     8       1
     8       0
     8       2
     8       74
     0       900
     0       45
     0       45
     8       85
     8       43
     8       4
     8       43
     8       90
     0       455

Output to be expected is as below



    22 (end 8  value(74) - start 8 value(56))
    5  (end 8  value(90) - start 8 value(85))


Upvotes: 2

Views: 94

Answers (1)

jezrael
jezrael

Reputation: 862911

Use:

#compare 8 in flag column
m = df['flag'].eq(8)
#create consecutive groups and filter by mask
g = m.ne(m.shift()).cumsum()[m]

#aggregate last and first by groups
df = df['values'].groupby(g).agg(['last','first']).reset_index(drop=True)
#get difference
df['diff'] = df['last'] - df['first']
print (df)
   last  first  diff
0    74     56    18
1    90     85     5

Upvotes: 1

Related Questions