Home > Blockchain >  Substract two row values in dataframe python
Substract two row values in dataframe python

Time:04-17

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

CodePudding user response:

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

CodePudding user response:

You can use .shift(-1):

df['time'] = df['left'] - df['left'].shift(-1)

or if you need it as a list:

(df['left'] - df['left'].shift(-1)).tolist()

  • Related