Skip to content
Advertisement

Substract two row values in dataframe python

Currently I have a sort of dataframe where I want to substract value from current row from the previous one.

example: df = pd.Datafame([1,4,3,5,6],columns = [“time”)])

left
1
4
3
5
6

I want to iterate over these rows and store it in a list. So the list will get like this [-3,1,-2,-1].

So far I have this

 list = []
    
    for index, row in df.iterrows():
          list.append(row['time'])

Now the for loop just stores the values in the list when it comes across the row. How can I change it that it substracts the current value from the previous one and stores it in a list?

Your help is appreciated

Advertisement

Answer

df['time'].diff(-1).tolist()[:-1]
>>> [-3.0, 1.0, -2.0, -1.0]
Advertisement