Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value from one column as variable for subtraction

Tags:

python

pandas

i have a data frame with XY's and distances. what i am trying to do is store the distance as a variable and subtract it from the next distance if X or Y has a value greater than 0

here is a sample df

dist     x      y
  0    12.93   99.23
200     0        0
400     0        0
600     0        0
800     0        0
1000    12.46   99.14
1200     0        0
1400     0        0
1600     0        0
1800     0        0
2000    12.01   99.07

and this is new df

dist     x      y
  0    12.93   99.23
200     0        0
400     0        0
600     0        0
800     0        0
  0    12.46   99.14
 200     0        0
 400     0        0
 600     0        0
 800     0        0
2000    12.01   99.07 

the last value doesn't matter, but technically, it would be 0.

the idea is that at every know XY, assign the distance as 0 and subtract that distance until the next known XY in the above example, the distances are rounded numbers, but in reality, they could be like

132.05
19.999
1539.65

and so on

like image 213
Messak Avatar asked Mar 13 '26 04:03

Messak


1 Answers

Check with transform

df.dist-=df.groupby(df.x.ne(0).cumsum())['dist'].transform('first')
df
Out[769]: 
    dist      x      y
0      0  12.93  99.23
1    200   0.00   0.00
2    400   0.00   0.00
3    600   0.00   0.00
4    800   0.00   0.00
5      0  12.46  99.14
6    200   0.00   0.00
7    400   0.00   0.00
8    600   0.00   0.00
9    800   0.00   0.00
10     0  12.01  99.07
like image 84
BENY Avatar answered Mar 14 '26 16:03

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!