Skip to content
Advertisement

(python) subtract value in a list from value in the same list in a for loop / list comprehension

suppose i have

JavaScript

in a for loop I want to subtract the value i from the value that comes right after. In the above example: 4-3, 6-4, 8-6, 13-8. (and i want to skip the first value) desired result

JavaScript

can i do this in a for loop / list comprehension?

more specifically do I want to do this in a dataframe

JavaScript

and after the operation

JavaScript

I have tried for loops, lambda functions and list comprehensions and trying to access the positional index with enumerate() but I can’t figure out how to access the value just before the value from which I want to subtract from

edit: answers below worked. thank you very much!

Advertisement

Answer

You should use shift to access the next row:

JavaScript

Or, using diff with fillna:

JavaScript

Output:

JavaScript

For a pure python solution:

JavaScript

Output: [3, 1, 2, 2, 5]

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement