Home > front end >  Take the difference of each value from the value before it in python
Take the difference of each value from the value before it in python

Time:04-26

I have csv file has values like this in one column:

1
9
5
7
3

How can I compute the difference between :

1-0=1   #(A1)
9-1=8   #(A2-A1)
5-2=3   #(A3-A2)
7-3=4   #(A4-A3)
3-7= -4  #(A5-A4)

This is the result :

1 8 3 4 -4

and put the result in the second column for the same csv file ?

CodePudding user response:

data = {'Numbers' : [234,-435,38,56,-4567,34,998]}
df = pd.DataFrame(data)
df['diff'] = df['Numbers'].rolling(window=2).apply(lambda x: x.iloc[1] - x.iloc[0]).fillna(df.Numbers.iloc[0])

First row will be NaN so to avoid that add fillna to zero

Output:

   Numbers    diff
0      234   234.0
1     -435  -669.0
2       38   473.0
3       56    18.0
4    -4567 -4623.0
5       34  4601.0
6      998   964.0
  • Related