Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading